Gregorian Calendar and date before 1970 - java

How can i fix the variable "time" for the gregorian calendar date before 1970. Or what was the unit of the variable "time" of gregorian calendar for the date before 1970?
I use hibernate for the object-relational mapping. And the data I'm trying to Save to my database is a date type gregorian calendar. But whenever the date is less than 1970, my application crash.

Timestamps before Epoch (1970 Jan 1st) are represented by negative numbers. Have a look at this SO answer to see an example.
If your application "crashes" (whatever that means), you need to look how is it represented in the database and how is it mapped.

tl;dr
ZonedDateTime.of(
LocalDate.of( 1969 , Month.DECEMEBER , 25 ) ,
LocalTime.NOON ,
ZoneId.of( "Africa/Tunis" )
).toInstant()
Crash?
You have not presented enough information to diagnose your crash.
Beware that the date-time capabilities of various databases varies widely. The SQL standard barely touches on the topic of date-time handling, so little is required. Some databases have quite limited support. Any serious enterprise-oriented database should be able to easily store moments going many centuries both in the past as well as the future.
java.time
Use the java.time classes added to Java 8 and later. These types are apparently now supported in Hibernate (I’m not a user).
Internally, moments after the epoch of 1970-01-01T00:00Z (first moment of 1970 in UTC) are represented as a count of nanoseconds, a positive number. For moment before the epoch, a negative number of nanoseconds. But you should not really care. Just use the java.time classes as intended, and never see that count number.
If you were to want noon of Christmas Day in 1969 in New Zealand:
LocalTime lt = LocalTime.NOON ;
LocalDate ld = LocalDate.of( 1969 , Month.DECEMEBER , 25 ) ;
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Database
With JDBC 4.2 and later, you can directly exchange these java.time types with your database. No need for numbers or strings. The old java.sql.Timestamp and related classes are now legacy, and can be forgotten.
Adjust your moment from its time zone to UTC, extract a Instant. Same simultaneous moment, same point on the timeline, but viewed through the lens of the wall-clock time used by the people of a particular region.
Instant instant = zdt.toInstant() ;
Pass to your database for a column of type TIMESTAMP WITH TIME ZONE.
myPreparedStatement.setObject( … , instant ) ;
And retrieval.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
ZonedDateTime zdt = instant.atZone( ZoneId.of( "America/Montreal" ) ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Cant you use Calender class?
public class DatePrint {
public static void main(String[] argv) {
Calendar c = new GregorianCalendar(1900, 10, 11);
System.out.println(c.get(Calendar.DAY_OF_MONTH) + " "
+ c.get(Calendar.MONTH) + ", " + c.get(Calendar.YEAR) + " "
+ c.get(Calendar.ERA));
}
}

Related

Change the time based on the gmt area on Android

I'm a beginner in android development and I've been searching for hours to find an answer for my question but I didn't really understand anything I found.
The match between 2 teams is starting at 20:00 gmt and I want to make it + - based on the area. For example in germany +1 gmt the time should be 21:00. I only want the hours and minutes format like that.
tl;dr
OffsetDateTime
.of(
LocalDate.of( 2021 , Month.MARCH , 23 ) ,
LocalTime.of( 20 , 0 ) ,
ZoneOffset.UTC
) // Returns a `OffsetDateTime` object.
.atZoneSameInstant(
ZoneId.of( "Europe/Berlin" )
) // Returns a `ZonedDateTime` object.
.toLocalTime() // Returns a `LocalTime` object.
.toString() // Returns a `String` object, with text in standard ISO 8601 format.
21:00
Details
Location does not necessarily correlate to time zone. Users choose their time zone as a preference. Servers should generally be set to UTC (an offset of zero). You can get the JVM’s current default time zone by calling ZoneId.systemDefault. If crucial, you should explicitly ask the user to confirm their desired zone.
I only want the hours and minutes format like that.
Date-time objects are not text, and do not have a "format". Think in terms of the logic needed for handling date-time values rather than in terms of manipulating strings.
starting at 20:00 gmt and I want to make it + - based on the area
Representing that 8 PM in UTC (the new GMT):
LocalDate tomorrow = LocalDate.now( ZoneOffset.UTC ).plusDays( 1 ) ;
LocalTime eightPM = LocalTime.of( 20 , 0 ) ;
OffsetDateTime odt = OffsetDateTime.of( tomorrow , eightPM , ZoneOffset.UTC ) ;
For example in germany +1 gmt the time should be 21:00
Define your desired time zone.
ZoneId z = ZoneId.of( "Europe/Berlin" ) ;
Adjust from the OffsetDateTime to a ZonedDateTime.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;
See that code run live at IdeOne.com.
odt.toString(): 2021-02-17T20:00Z
zdt.toString(): 2021-02-17T21:00+01:00[Europe/Berlin]
The odt & zdt objects seen here both refer to the very same simultaneous moment, the same point on the timeline.
This has all been covered many times before on Stack Overflow. Search to learn more.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
It's not Android specific but just a general question about Java.
Use Calendar and SimpleDateFormat like this:
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.set(2021, 1, 16, 20, 00, 00); // 2021-02-16T20:00:00 GMT
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
System.out.println(simpleDateFormat.format(calendar.getTime()));
Set (input) your date as GMT. Then format it GMT+01:00 with SimpleDateFormat and print (output) it.

GregorianCalendar in Android (add Calendar.HOUR_OF_DAY vs Calendar.HOUR)

To add an hour to current time, can I use this?
Calendar mcalendar = new GregorianCalendar();
mcalendar.add(Calendar.HOUR_OF_DAY, 1); //I plan to use 24 hours format
I see many examples using instead:
Calendar mcalendar = Calendar.getInstance();
mcalendar.add(Calendar.HOUR, 1);
tl;dr
Duration duration = Duration.ofHours( 1 ) ;
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( zoneId ).plus( duration ) ;
DateTimeFormatter f = DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.GERMANY) ;
String output = zdt.format( f ) ;
Sonntag, 27. Dezember 2020 um 22:58:52 Nordamerikanische Ostküsten-Normalzeit
java.time
The modern solution uses the java.time classes. Never use Calendar or GregorianCalendar.
UTC
Capture the current moment as seen in UTC. Use Instant.
Instant instant = Instant.now() ; // Capture the current moment as seen in UTC.
Define a span-of-time unattached to the timeline.
Duration duration = Duration.ofHours( 1 ) ;
Addition.
Instant instantHourLater = instant.plus( duration ) ;
Zoned
You may want to see the time-of-day and date of that moment as seen through the wall-clock time used by the people of a particular region. Apply a time zone (ZoneId) to get a ZonedDateTime object. Same moment, same point on the timeline, different wall-clock time.
ZoneId zoneId = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( zoneId ) ;
Or, skip the Instant and the Duration.
ZonedDateTime zdt = ZonedDateTime.now( zoneId ).plusHours( 1 ) ;
Text
You said:
I plan to use 24 hours format
The classes such as Instant, OffsetDateTime, and ZonedDateTime represent a moment, a point on the timeline. They have nothing to do with text. They do not have a “format”. They can parse text representing a moment, and they can produce text representing a moment. But internally they have their own way of representing that moment, without any formatted text.
To produce text in a particular format, use DateTimeFormatter class with FormatStyle and Locale. This has been covered many many times already on Stack Overflow. So search to learn more.
DateTimeFormatter f = DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
;
String output = zdt.format( f ) ;
See this code run live at IdeOne.com.
output: dimanche 27 décembre 2020 à 22 h 51 min 57 s heure normale de l’Est
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 brought some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android (26+) bundle implementations of the java.time classes.
For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Calendar mcalendar = new GregorianCalendar();
The GreogorianCalendar is a subclass of the abstract class Calendar. Therefore what you are doing here is referencing an instance of the GregorianCalendar to the Calendar therefore all the abstract methods in Calendar will follow the implementation of GregorianCalendar
But since your purpose is to add Hours.
You can go ahead with Calendar mcalendar = Calendar.getInstance(); as it retrieves an instance to the current with the the current Locale.
However, if you want to change your Locale, pass in the parameter into the getInstance() method and an instance of the specified Locale will be generated for you.
Refer: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#getInstance(java.util.Locale)
And if you want to use Hours:
Do the following:
Do not use HOUR variable as this is only for 12 hour times. Use Calendar.HOUR_Of_DAY to deal with 24 hour timings.

Schedule that runs every day at a specific time with hh:mm:ss

I'm trying to run code at a specific time every day, but with hh:mm:ss. I'm specifically, trying to run it at 5PM EST every day, so Timezones needs to be accounted for.
Here's my attempt, in kotlin:
val timer = Timer()
val format = SimpleDateFormat("hh:mm:ss")
val date = format.parse("11:07:09")
timer.schedule(object : TimerTask() {
override fun run() {
// code here
}
}, date)
I wasn't able to get that working, and even if I did, I'm not sure how I'd add timezones to it as well.
How can I do this?
tl;dr
java.util.Date
.from(
ZonedDateTime.of(
LocalDate.now( ZoneId.of( "America/Montreal" ) ) ,
LocalTime.parse( "11:07:09" ) ,
ZoneId.of( "America/Montreal" )
)
.toInstant()
)
Details
A java.util.Date represents a date with a time-of-day in UTC.
You have ignored the date and the zone/offset.
Your result is apparently defaulting to 11 AM on January 1, 1970.
java.time
Also, the terrible Date and SimpleDateFormat classes were supplanted years ago by the java.time classes.
Represent your target time-of-day.
LocalTime lt = LocalTime.parse( "11:07:09" ) ;
Get current date, today’s date. Requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;
Put these together to determine a moment.
ZonedDateTime zdt = ZonedDateTime.of( today , lt , z ) ; // Time-of-day will be adjusted if not valid on that date in that zone.
Adjust into UTC. Same moment, same point on the timeline, different wall-clock time.
Instant instant = zdt.toInstant() ; // Adjust from zone to UTC.
Avoid the legacy date-time classes. But if you must interoperable, you can convert back and forth by calling new methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ;
You will likely want to improve this code to see if your desired moment has already passed. To compare, use isAfter and isBefore methods.
Executors
The Timer class has been supplanted by the executor framework. Search the Oracle Java Tutorials and Stack Overflow to learn more.
With an executor, you can schedule a task to run at a certain moment. But you do so indirectly, by specifying a waiting period rather than a time-of-day. The scheduling executor takes an argument for an initial delay. You can calculate that delay as a span of time between the current moment and the desired moment.
To calculate that span of the time, use the Duration class.
Duration d = Duration.between( Instant.now() , instant ) ;
Keep in mind that you cannot expect split-second perfect timing of your tasks to be executed. The scheduling of your JVM on the host OS, and of your Java threads within the JVM, can involve delays.
Of course, you will also need to record a history of your tasks when completed. When your app does a shutdown, then relaunch, it needs to study the history to figure out how to set up a new schedule. This issue is beyond the scope of this Answer. Read up on writing files, using a database, or relying on some other persistence scheme.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Java Date and Timestamp from instance of ZonedDateTime UTC

I have a java application in which I would like the time in UTC. Currently, the code uses a mix of java.util.Date and java.sql.Timestamp. To get the time in UTC, the programmer before me used:
For Date:
Date.from(ZonedDateTime.now(ZoneOffset.UTC)).toInstant();
For Timestamp:
Timestamp.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
However I have run multiple tests myself with this code and both of these lines return the current date/time(in my current timezone). From everything I have read it appears that Date/Timestamp does not have a zoneOffset value, but I cannot find a concrete statement of this.
Is there anyway to keep the timeZone (UTC) within the Date or Timestamp objects, or do I need to do some refactoring and use the actual ZonedDateTime object throughout my application? Also will this ZonedDateTime object be compatible with the current Timestamp object for sql?
Example:
public static void main (String args[])
{
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
Timestamp timestamp = Timestamp.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
Date date = Date.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
System.out.println("ZonedDateTime: " + zonedDateTime);
System.out.println("Timestamp: " + timestamp);
System.out.println("Date: " + date);
}
Output:
ZonedDateTime: 2017-04-06T15:46:33.099Z
Timestamp: 2017-04-06 10:46:33.109
Date: Thu Apr 06 10:46:33 CDT 2017
tl;dr
Instant.now() // Capture the current moment in UTC with a resolution up to nanoseconds.
Use only java.time classes. Avoid the troublesome old legacy date-time classes added before Java 8.
Using java.time
The programmer before you was making use of the new modern java.time classes that now supplant the notoriously troublesome old legacy date-time classes such as Date, Calendar, Timestamp.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). To get the current moment in UTC is utterly simple: Instant.now.
Instant instant = Instant.now();
Converting
You should stick to the java.time classes, and avoid the legacy classes. But if absolutely necessary such as interfacing with old code not yet updated for java.time, you may convert to/from java.time. Look to new methods on old classes. The legacy class java.util.Date equivalent is Instant.
java.util.Date d = java.util.Date.from( myInstant); // To legacy from modern.
Instant instant = myJavaUtilDate.toInstant(); // To modern from legacy.
JDBC
Avoid the legacy date-time classes. Use java.time classes instead.
Your JDBC 4.2 compliant driver may be able to directly address java.time types by calling PreparedStatement::setObject and ResultSet::getObject.
myPreparedStatement.setObject( … , instant ) ;
… and …
Instant instant = myResultSet.getObject( … , Instant.class ) ;
If not, fall back to using the java.sql types, but as briefly as possible. Use new conversion methods added to the old classes.
myPreparedStatement.setTimestamp( … , java.sql.Timestamp.from( instant ) ) ;
… and …
Instant instant = myResultSet.getTimestamp( … ).toInstant() ;
No need for ZonedDateTime
Notice that we had no need for your mentioned ZonedDateTime as you said you were only interested in UTC. The Instant objects are always in UTC. That means that original code you quoted:
Date.from(ZonedDateTime.now(ZoneOffset.UTC)).toInstant();
…could have simply been shortened to:
Date.from( Instant.now() ) ;
Note that java.util.Date is always in UTC as well. However, its toString unfortunately applies the JVM’ current default time zone implicitly while generating the String. This anti-feature creates no end of confusion as you can see by searching on Stack Overflow.
If you want to see your Instant object’s UTC value through the lens of a region’s wall-clock time, assign a time zone ZoneId to get a ZoneDateTime.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as CDT or EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdt = instant.atZone( z );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
In Java, Date represents a point in time. It's not related to timestamp. When you call toString() method of a Date object, it converts that time to Platform's default Timestamp, e.g. Following will print date/time in UTC (as it sets default timezone to UTC):
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneOffset.UTC);
Timestamp timestamp = Timestamp.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
Date date = Date.from(ZonedDateTime.now(ZoneOffset.UTC).toInstant());
System.out.println("ZonedDateTime: " + zonedDateTime);
System.out.println("Timestamp: " + timestamp);
System.out.println("Date: " + date);

Show ISO-8601 date+time in current time?

for example, 2012-10-30T22:30:00+0300 need to be shown in 2012-10-30T22:30:00-0600 (the local time for example)
need to implement in java (android app)
how can I manage doing that?
That's what a Date is: a universal instant in time. Choose the appropriate time zone when displaying it, and you'll have the time string you want:
Date now = new Date();
DateFormat df = df.getDateTimeInstance();
System.out.println(df.format(now)); // now, displayed in the current time zone (examle: Germany)
df.setTimeZone(theLondonTimeZone);
System.out.println(df.format(now)); // now, displayed in the time zone of London
tl;dr
OffsetDateTime
.parse(
"2012-10-30T22:30:00+0300" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" )
)
.toInstant()
.atZone(
ZoneId.of( "Europe/London" )
)
.toString()
2012-10-30T19:30Z[Europe/London]
java.time
The modern solution uses the java.time classes.
Define a formatter to match your input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ssX" ) ;
Parse the input as a OffsetDateTime.
String input = "2012-11-05T13:00:00+0200" ;
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2012-11-05T13:00+02:00
Tip: Always include the COLON character as a delimiter between the hours and minutes of the offset. We could then skip the custom formatting pattern: OffsetDateTime.parse( "2012-11-05T13:00+02:00" ).
Adjust to UTC, an offset of zero hours-minutes-seconds, by extracting a Instant object.
Instant instant = odt.toInstant() ;
In standard ISO 8601 format, the Z on the end means UTC (offset of zero). Pronounced “Zulu”.
instant.toString(): 2012-11-05T11:00:00Z
Adjust into London time.
ZoneId zLondon = ZoneId.of( "Europe/London" ) ;
ZonedDateTime zdtLondon = instant.atZone( zLondon ) ;
zdtLondon.toString(): 2012-11-05T11:00Z[Europe/London]
Adjust to another time zone.
ZoneId zMontreal = ZoneId.of( "America/Montreal" );
ZonedDateTime zdtMontreal = instant.atZone( zMontreal );
zdtMontreal.toString(): 2012-11-05T06:00-05:00[America/Montreal]
All these objects (odt, instant, zdtLondon, and zdtMontreal) represent the very same simultaneous moment, the same point on the timeline. Same moment, different wall-clock time.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
https://i.stack.imgur.com/eKgbN.png
Table of which java.time library to use with which version of Java or Android
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Using joda time library solved my problem optimally, using dateTime & dateTime zone like following:
DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis();
DateTime dt = new DateTime();
DateTime dt2 = new DateTime();
dt = DateTime.parse("2012-11-05T13:00:00+0200");
System.out.println(dt.toString());
dt2 = DateTime.parse("2012-11-05T21:45:00-08:00");
DateTimeZone dtz = dt2.getZone();
System.out.println(dt.withZone(dtz).toString());

Categories