Date time String + TimeZone - java

I have a String representation of a local date time, and a Java TimeZone.
I am trying to get output in the format MM/dd/yyyy HH:mm:ssZ but I can't figure out how to create a Calendar or JodaTime object with the correct date time and timezone. How do you get a TimeZone converted to a value that can be parsed by SimpleDateFormat 'Z' or 'z'?
TimeZone tz = TimeZone.getTimeZone("America/Chicago");
String startDate = "08/14/2014 15:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance(tz);
cal.setTime(sdf.parse(startDate));
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ssZ");
and
sdfZ.format(cal.getTime())
returns
08/14/2014 15:00:00-0400
which is EST.
Is the only workaround to create a Calendar or Joda DateTime and set the individual year/month/day/hour/min values by parsing the string "08/14/2014 15:00:00" ?

Calendar getTime() - Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(01-01-1970 00:00 GMT)") irrespective of which timezone you are displaying. But hour of day in different TimeZone will be different. get(Calendar.HOUR_OF_DAY)
You should try
sdfZ.setTimeZone(tz);

tl;dr
ZonedDateTime zdt = ZonedDateTime.now( ZoneId.of( "America/Chicago" ) ) ;
String output = zdt.toInstant().toString() ;
2016-12-03T10:15:30Z
java.time
Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time classes.
Instant
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now();
Call toString to generate a String in standard ISO 8601 format. For example, 2011-12-03T10:15:30Z. This format is good for serializing date-time values for data storage or exchange.
String output = instant.toString(); // Ex: 2011-12-03T10:15:30Z
Time zone
Assign a time zone.
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime zdt = instant.atZone( z );
As a shortcut, you can skip over using Instant.
ZonedDateTime zdt = ZonedDateTime.now( z );
Calling toString on ZonedDateTime gets you an extended version of standard ISO 8601 format where the name of the time zone is appended in square brackets. For example, 2007-12-03T10:15:30+01:00[Europe/Paris].
String output = zdt.toString(); // Ex: 2007-12-03T10:15:30+01:00[Europe/Paris]
DateTimeFormatter
The DateTimeFormatter class has a predefined formatter constant for your desired output: DateTimeFormatter.ISO_LOCAL_DATE_TIME
String output zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_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.
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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.

Related

Java - Parsing a JLabel to java.util.Date

I'm simply trying to parse a string in JLabel to a date using a simpleDateFormatter(). Based On everything I've searched online, this code should work. However, I'm receiving the "cannot find symbol - method parse(java.lang.String)" error during compiliation. Any advice on how to resolve the issue would be greatly appreciated.
The JLabel in question was populated with a date from a database query using JDBC.
Additionally, I'm aware that that java.util.Date has been deprecated, but would still like to use it for this.
Code Snippet:
private Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
private JLabel dateDataLabel = new JLabel("");
private void setAndParseLabel()
{
dateDataLabel.setText(formatter.format(validatePass.eventDate));
java.util.Date aDate = formatter.parse(dateDataLabel.getText());
}
tl;dr
You are ignoring crucial issue of time zone. You are unwittingly parsing the input as a value in UTC.
You are using terrible old date-time classes that were supplanted years ago. Use java.time instead.
Example code:
LocalDateTime
.parse(
"2018-01-23 13:45".replace( " " , "T" ) // Comply with standard ISO 8601 format by replacing SPACE with `T`. Standard formats are used by default in java.time when parsing/generating strings.
) // Returns a `LocalDateTime` object. This is *not* a moment, is *not* a point on the timeline.
.atZone( // Apply a time zone to determine a moment, an actual point on the timeline.
ZoneId.of( "America/Montreal" )
) // Returns a `ZonedDateTime` object.
.toInstant() // Adjust from a time zone to UTC, if need be.
java.time
The modern approach uses the java.time classes.
Your input string is almost in standard ISO 8601 format. To fully comply, replace that SPACE in the middle with a T.
String input = "2018-01-23 13:45".replace( " " , "T" ) ;
Parse as a LocalDateTime because your input has no indicator of time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime by definition does not represent a moment, is not a point on the timeline. It represents potential moments along a range of about 26-27 hours (the range of time zones around the globe).
To determine a moment, assign a time zone (ZoneId) to get a ZonedDateTime object.
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 EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
If you wish to see that same moment through the wall-clock time of UTC, extract an Instant.
Instant instant = zdt.toInstant() ; // Adjust from some time zone to UTC.
Avoid java.util.Date where feasible. But if you must interoperate with old code not yet updated to java.time, you can convert back-and-forth. Call new conversion methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ; // Going the other direction: `myJavaUtilDate.toInstant()`
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.text.Format does not have method parse, so the code does not compile.
You can refer it by java.text.DateFormat:
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
There is no method parse in java.text.Format. Use java.text.DateFormat instead:
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");

Java Calendar object, setting date and time separately

When creating a calendar object and setting the date/time using SimpleDateFormat to parse a string, is it possible to set the date and time in two separate lines of code? For example, in my SQLite db the date (mm-dd-yyyy) is stored in a separate column from the time (hh:mm). Is it kosher to do something like the following:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat sdfTime = new SimpleDateFormat("hh:mm zzz");
cal.setTime(sdfDate.parse(DATE));
cal.setTime(sdfTime.parse(TIME));
Would the second cal.setTime line reset the date portion of the calendar object to now and just change the time?
Yes it would.
setTime() sets the the time regardless of the fact that a date contained no time value (00:00:00) or no date value (01.01.1970).
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdfDate = new SimpleDateFormat("MM-dd-yyyy hh:mm zzz");
cal.setTime(sdfDate.parse(DATE+ " " + TIME));
Should work out for you.
tl;dr
ZonedDateTime.of(
LocalDate.parse( "12-23-2015" , DateTimeFormatter.ofPattern( "MM-dd-yyyy") ) ,
LocalTime.parse( "21:43" ) ,
ZoneId.of( "Pacific/Auckland" )
)
.toString()
2015-12-23T21:43+13:00[Pacific/Auckland]
Details
The Answer by Jan is correct.
java.time
Alternatively, you could use the new date-time framework, java.time.
The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
If your inputs lacked an offset-from-UTC, then we could treat the date and the time-of-day separately. The new classes include LocalDate to represent a date-only value without a time-of-day, and LocalTime to represent a time-only value without a date. Then you can combine them and adjust into their intended time zone.
DateTimeFormatter formatterDate = DateTimeFormatter.ofPattern( "MM-dd-yyyy");
LocalDate localDate = LocalDate.parse( "12-23-2015" , formatterDate );
LocalTime localTime = LocalTime.parse( "21:43" );
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.of( localDate , localTime , zoneId );
But your time string does contain an offset-from-UTC. So we should take the same approach as the Answer by Jan, concatenate the pair of strings and then parse.
String input = "12-23-2015" + " " + "21:43-05:00" ;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "MM-dd-yyyy HH:mmxxx");
ZonedDateTime zdt = ZonedDateTime.parse( input , formatter );
ISO 8601
By the way, in the future when serializing a date, a time, or a date-time to a string such as you did in your SQLite database I strongly recommend using the standard ISO 8601 formats: YYYY-MM-DD, HH:MM, and YYYY-MM-DDTHH:MM:SS.S±00:00. For example, 2007-12-03T10:15:30+01:00. These formats are standardized, easy for humans to read and discern, and easy for computers to parse without ambiguity.
The java.time framework parses and generates strings in these formats by default. Also, java.time extends ISO 8601 by appending the name of the time zone in square brackets. For example, 2007-12-03T10:15:30+01:00[Europe/Paris].
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or java.sql.* classes.
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.

formatted string to date conversion without changing format in java

I have formatted date in the form of string and i want it in date format without changing formatted pattern
here is my code
Date currDate = new Date();//Fri Oct 31 03:48:24 PDT 2014
String pattern = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern);
String formattedDate= formatter.format(currDate);//2014-10-31 04:23:42
here am getting in "yyyy-MM-dd hh:mm:ss" format and the same format i want it in date.
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date paidDate = sdf.parse(formattedDate);
System.out.println(pattern + " " + paidDate);//Fri Oct 31 03:48:24 PDT 2014
but i am getting result as Fri Oct 31 03:48:24 PDT 2014, so pls help me to get result as 2014-10-31 04:23:42 in date format
If I understood your problem correctly:
System.out.println(pattern + " " + sdf.format(paidDate);
You seem to be under the mistaken impression that a Date object somehow encodes format of the original date. It doesn't.
So ... when you do this:
Date paidDate = sdf.parse(formattedDate);
it does not "remember" original format of the text form of the date in paidDate. And it cannot. If you want to print / unparse a Date in any format than the default one, you should use a DateFormat and call its format method. Calling toString() will just give you the date in the default format.
Try this.
System.out.println(formatter.format(paidDate));
tl;dr
Do not conflate a date-time object with a string representing its value. A date-time object has no “format”.
ZonedDateTime.now( // Instantiate a `ZonedDateTime` object capturing the current moment.
ZoneId.of( "Africa/Tunis" ) // Assign this time zone through which we see the wall-clock time used by the people of this particular region.
).format( // Generate a string representing the value of this `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) // Define a formatting pattern to match your desire.
)
2018-03-10 07:36:23
Calling ZonedDateTime::toString generates a string in standard ISO 8601 format.
2018-03-10T07:36:23.595362+01:00[Africa/Tunis]
Date-time object has no “format”
You are confusing a date-time object in Java, or a date-time value stored in a database, with a textual representation. You can generate a string from a date-time object (or database value), but that string is separate and distinct from the value it represents. Do not conflate a string with its generating creator.
java.time
Avoid using the troublesome old date-time classes such as Date, Calendar, and SimpleDateFormat. Instead, use Instant, ZonedDateTime, and DateTimeFormatter classes, respectively.
If you have an input string such as 2014-10-31 04:23:42, replace the SPACE in the middle with a T to comply with ISO 8601 standard format. The java.time classes use ISO 8601 formats by default when parsing/generating strings.
String input = "2014-10-31 04:23:42".replace( " " , "T" ) ;
That input lacks any indicator of time zone or offset-from-UTC. So parse as a LocalDateTime which purposely lacks any concept of zone/offset.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
ldt.toString(): 2014-10-31T04:23:42
A LocalDateTime does not represent a moment, is not a point on the timeline. To determine an actual moment, you must supply the context of a zone or offset.
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ; // Now we have an actual moment, a point on the timeline.
To capture the current moment in UTC, use Instant.
Instant instant = Instant.now() ;
Adjust into another zone.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-03-10T07:36:23.595362+01:00[Africa/Tunis]
I do not recommend generating strings lacking an indicator of zone/offset. But if you insist, use the built-in DateTimeFormatter and then replace the T in the middle with a SPACE to get your desired format.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
2018-03-10 07:36:23.595362
If you really do not want the fractional second, then define your own formatting pattern.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = zdt.format( f ) ;
2018-03-10 07:36:23
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, 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 (<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.

Comparing string date with today's date

So I have a string which is "2014-06-30 15:27" and if it is today's date it should only return "15:27" else "30/06/2014". I've already tried simpleDateFormat.parse but it didn't work very well.
holder.data.setText(mensagem.getDate());
final String stringDate = "2014-07-17 23:59";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = inputFormat.parse(stringDate);
Calendar calendarDate = Calendar.getInstance();
calendarDate.setTime(date);
Calendar midnight = Calendar.getInstance();
midnight.set(Calendar.HOUR_OF_DAY, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MILLISECOND, 0);
if (calendarDate.compareTo(midnight) >= 0)
{
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
System.out.println(timeFormat.format(date));
}
else
{
SimpleDateFormat dateTimeForm = new SimpleDateFormat("dd/MM/yyyy HH:mm");
System.out.println(dateTimeForm.format(date));
}
LocalDateTime
First parse the string as a LocalDateTime. Replace the SPACE in the middle with T to comply with standard ISO 8601 format. The java.time classes support ISO 8601 formats by default.
LocalDateTime ldt = LocalDateTime.parse ( "2014-06-30 15:27".replace ( " " , "T" ) );
ldt.toString(): 2014-06-30T15:27
Such a value has no real meaning. The input string lacked any clue about offset-from-UTC or time zone. So we do not know if this is 3 PM in Auckland NZ or 3 PM in Québec Canada, two very different moments. You should to assign the offset or time zone indicated by your business situation. Search Stack Overflow for how to do this, focussing on classes OffsetDateTime and ZonedDateTime. I'll skip over this crucial issue for now.
LocalDate
Extract a date-only value. The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = ldt.toLocalDate();
Today
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
Comparison
You can compare LocalDate objects by calling methods such as compareTo, equals, isEqual, isBefore, isAfter.
if( today.isEqual( ld ) ) {
return ldt.toLocalTime();
} else {
return ld;
}
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.
As the java.time library is the recommended way to use date and time. So, to compare current date with a string date you need to first convert date in string format to java.time.LocalDate :
LocalDate paresedStringDate = LocalDate.parse("2022-11-10");
After that you can get the current date using below code:
LocalDate currentDate = LocalDate.now();
And then you can compare both the current date and parsed string date to check if both are same using below code:
if (paresedStringDate.compareTo(currentDate) == 0) {
//do what you want to do here
}
Simply use the Date class...
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date exitdate = df.parse("2019-01-17");
Date currdate = new Date();
long diff = currdate.getTime() - exitdate.getTime();
long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
if(days==0)
{
System.out.println("IS TRUE"+currdate.toString());
return true;
}

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