Store date and time from Java in SQL SERVER - java

I am trying to store datetime from Java using GregorianCalendar class in SQL SERVER, however it only stores date. I need to store the date and time in SQL SERVER.
this is the code i implemented
CallableStatement asignarTurno=conexionBBDD
.getConexionBBDD().prepareCall("{call asignarTurno(?,?,?,?,?,?)}");
//GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second)
GregorianCalendar h=new GregorianCalendar(2000, 1, 1, 8, 30,0);
java.sql.Date date = new java.sql.Date(h.getTimeInMillis());
asignarTurno.setInt(1,1);
asignarTurno.setDate(2,date);
asignarTurno.setDate(3,date);
asignarTurno.setDate(4,date);
asignarTurno.setString(5, "000");
asignarTurno.setString(6,"0001");
asignarTurno.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
}

Multiple problems with your code.
Never use the terrible date-time classes such as GregorianCalendar and Date. These were supplanted years ago by the modern java.time classes defined in JSR 310.
You are trying to represent a moment having a date, a time-of-day, and an implicit time zone (GregorianCalendar) into a data type that pretends to hold only a date (java.sql.Date). Square peg, round hole.
Date-only
The DATE type in Microsoft SQL Server is akin to the SQL-standard type DATE, holding only a date, without a time-of-day, and without a time zone. So use java.time.LocalDate in Java.
LocalDate ld = LocalDate.of( 2000 , Month.FEBRUARY , 1 ) ;
myPreparedStatement.setObject( … , ld ) ;
And retrieval.
LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;
Moment
If you do indeed want to track moments, you must redefine your database column with an appropriate data type. In standard SQL, that would be TIMESTAMP WITH TIME ZONE. In Microsoft SQL Server, that would be datetimeoffset.
In Java, you would place your date at time-of-day in the context of a time zone. This produces a ZonedDateTime object.
LocalDate ld = LocalDate.of( 2000 , Month.FEBRUARY , 1 ) ;
LocalTime lt = LocalTime.of ( 8 , 30 ) ;
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Unfortunately, the JDBC 4.2 team inexplicably decided to require support for OffsetDateTime but not the two more commonly-used classes, Instant and ZonedDateTime. So for maximum portable code, use OffsetDateTime. If portability is not so important, test your JDBC driver to see if it optionally chose to support ZonedDateTime or Instant.
We could just call ZonedDateTime#toOffsetDateTime. But this would bring the offset used by that time zone at that moment. For clarity, I suggest instead adjusting to UTC. That is easily accomplished by extracting a Instant (always in UTC) from our ZonedDateTime. Then we convert to OffsetDateTime with an offset of zero, per JDBC 4.2 spec.
OffsetDateTime odt = zdt.toInstant().atOffset( ZoneOffset.UTC ) ;
Then pass to your prepared statement.
myPreparedStatement.setObject( … , odt ) ;
And retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
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….

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.

How to update a Timestamp field in MySql from a Java PreparedStatement?

My index.html has an <input type="datetime-local"> field and I need to update a MySql database with whatever value the user selects. My database field is currently a Timestamp. How can I create an update statement that allows me to update the database with this datetime-local value? I've tried many options and my current attempt is shown below; however, this does not work. I am doing this all in Java.
String updateStatement = "UPDATE cars SET reservation = ? WHERE uniqueID = ?";
pStmt = con.prepareStatement(updateStatement);
pStmt.setTimestamp(1, reservation);
pStmt.setTimestamp(2, someUniqueId);
tl;dr
To answer your specific code question (but this is the wrong way to handle appointments/reservations):
myPreparedStatement
.setObject(
1 ,
ZonedDateTime
.of
(
LocalDate.of( 2021 , Month.JANUARY , 23 ) ,
LocalTime.of( 15 , 30 ) ,
ZoneId.of( "Africa/Tunis" )
)
.toInstant()
.atOffset( ZoneOffset.UTC )
)
;
java.time
The TIMESTAMP type in MySQL is for tracking a moment, a specific point on the timeline, as seen from an offset of zero hours-minutes-seconds from UTC, resolving to microseconds. This maps to TIMESTAMP WITH TIME ZONE in standard SQL.
The appropriate match in Java would be java.time.Instant. This class also represents a moment as seen in UTC, but with finer resolution of nanoseconds.
Unfortunately, the JDBC 4.2 specification requires support for only one of the three types that track a moment: OffsetDateTime. Both Instant and ZonedDateTime are optional in JDBC 4.2. So your particular JDBC driver may or may not support Instant. This design decision by the JDBC team baffles me. Converting between Instant and OffsetDateTime is utterly simple, and should have been required by JDBC spec.
I am guessing you are letting users pick a date and a time-of-day within a particular time zone. But I'm not sure, as your neglected to detail your inputs.
LocalDate localDate = LocalDate.of( 2021 , Month.JANUARY , 23 ) ;
LocalTime localTime = LocalTime.of( 15 , 30 ) ;
ZoneId zoneId = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime zdt = ZonedDateTime.of( localDate, localTime , zoneId ) ;
To store in the database, let's adjust from a time zone to UTC (an offset of zero). Convert from ZonedDateTime to Instant, and then to OffsetDateTime with an offset of zero hours-minutes-seconds represented by the constant ZoneOffset.UTC.
OffsetDateTime odt = zdt.toInstant().atOffset( ZoneOffset.UTC ) ; // Use `OffsetDateTime` rather than `Instant` for maximum compatibility across JDBC 4.2 drivers.
Do not call PreparedStatement#setTimestamp. That method is now legacy, for the terrible java.sql.Timestamp class. Never use date-time classes outside the java.time package. Those legacy classes were supplanted years ago by the modern java.time classes defined in JSR 310.
Call PreparedStatement#setObject. The JDBC team has yet to define specific set… methods for the various java.time classes. Again, a design decision which baffles me. However, we can exchange the java.time objects using setObject/getObject.
myPreparedStatement.setObject( … , odt ) ;
Retrieval.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Tracking appointments
By the way, you mentioned the business problem is making restaurant reservations in the future. For this work, you are taking the wrong approach.
Such future appointments are not tracked as moments, are not specific points on the timeline. If politicians were to change the offset used by that time zone, your customers expect a restaurant reservation for 7 PM to stay at 7 PM, regardless of politicians moving the clock forward or backward. Similarly, a dental appointment for 3 PM four months from now should stay at 3 PM even if the politicians change the offset. And politicians around the world do enjoy changing their time zone offset. This happens surprisingly often, and with less and less forewarning.
Reservations/appointments should be tracked as date and time without time zone, storing time zone separately in second column of database. These types would be TIMESTAMP WITHOUT TIME ZONE in standard SQL, and DATETIME in MySQL. And use a text type for the time zone identifier. The matching type in Java would be LocalDateTime and ZoneId. At runtime for calendaring, combine to determine a moment with a ZonedDateTime.
I and other authors have covered this many times already on Stack Overflow. So 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….
Maybe your date format is incorrect.
reservation = System.currentTimeMillis();
UPDATE
Ok,I understand you.You should use String to receive the datetime-local value.
Because the format of datetime-local from frontend is yyyy-MM-ddTHH:mm, but the format of TimeStamp in Java(package java.sql) is yyyy-MM-ddTHH:mm:ss.
It lack the :ss, so can not receive.
Finally set timestamp after convert String to TimeStamp.
datetimeLocal = datetimeLocal.replaceAll("T", " ") + ":00";
Timestamp reservation = Timestamp.valueOf(datetimeLocal);

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.

Gregorian Calendar and date before 1970

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));
}
}

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