I am using Java 8
This is what my ZonedDateTime looks like
2013-07-10T02:52:49+12:00
I get this value as
z1.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)
where z1 is a ZonedDateTime.
I wanted to convert this value as 2013-07-10T14:52:49
How can I do that?
Is this what you want?
This converts your ZonedDateTime to a LocalDateTime with a given ZoneId by converting your ZonedDateTime to an Instant before.
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneOffset.UTC);
Or maybe you want the users system-timezone instead of hardcoded UTC:
LocalDateTime localDateTime = LocalDateTime.ofInstant(z1.toInstant(), ZoneId.systemDefault());
It looks like you need to convert to the desired time zone (UTC) before sending it to the formatter.
z1.withZoneSameInstant( ZoneId.of("UTC") )
.format( DateTimeFormatter.ISO_OFFSET_DATE_TIME )
should give you something like 2018-08-28T17:41:38.213Z
#SimMac Thanks for the clarity. I also faced the same issue and able to find the answer based on his suggestion.
public static void main(String[] args) {
try {
String dateTime = "MM/dd/yyyy HH:mm:ss";
String date = "09/17/2017 20:53:31";
Integer gmtPSTOffset = -8;
ZoneOffset offset = ZoneOffset.ofHours(gmtPSTOffset);
// String to LocalDateTime
LocalDateTime ldt = LocalDateTime.parse(date, DateTimeFormatter.ofPattern(dateTime));
// Set the generated LocalDateTime's TimeZone. In this case I set it to UTC
ZonedDateTime ldtUTC = ldt.atZone(ZoneOffset.UTC);
System.out.println("UTC time with Timezone : "+ldtUTC);
// Convert above UTC to PST. You can pass ZoneOffset or Zone for 2nd parameter
LocalDateTime ldtPST = LocalDateTime.ofInstant(ldtUTC.toInstant(), offset);
System.out.println("PST time without offset : "+ldtPST);
// If you want UTC time with timezone
ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdtPST = ldtUTC.toLocalDateTime().atZone(zoneId);
System.out.println("PST time with Offset and TimeZone : "+zdtPST);
} catch (Exception e) {
}
}
Output:
UTC time with Timezone : 2017-09-17T20:53:31Z
PST time without offset : 2017-09-17T12:53:31
PST time with Offset and TimeZone : 2017-09-17T20:53:31-08:00[America/Los_Angeles]
If z1 is an instance of ZonedDateTime, then the expression
z1.withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime()
evaluates to an instance of LocalDateTime with the string representation requested by the OP. This is illustrated by the following program:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
ZonedDateTime time = ZonedDateTime.now();
ZonedDateTime truncatedTime = time.truncatedTo(ChronoUnit.SECONDS);
ZonedDateTime truncatedTimeUtc = truncatedTime.withZoneSameInstant(ZoneOffset.UTC);
LocalDateTime truncatedTimeUtcNoZone = truncatedTimeUtc.toLocalDateTime();
System.out.println(time);
System.out.println(truncatedTime);
System.out.println(truncatedTimeUtc);
System.out.println(truncatedTimeUtcNoZone);
}
}
Sample output:
2020-10-26T16:45:21.735836-03:00[America/Sao_Paulo]
2020-10-26T16:45:21-03:00[America/Sao_Paulo]
2020-10-26T19:45:21Z
2020-10-26T19:45:21
I wanted to convert this value as 2013-07-10T14:52:49
👉 2013-07-10T02:52:49+12:00 ≠2013-07-10T14:52:49 at UTC
👉 2013-07-10T02:52:49+12:00 = 2013-06-09T14:52:49 at UTC (which is obtained by subtracting 12:00 hours of the offset from 2013-07-10T02:52:49).
Demo:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
class Main {
public static void main(String[] args) {
ZoneOffset zoneOffset = ZoneOffset.of("+12:00");
OffsetDateTime odtGiven = OffsetDateTime.of(LocalDateTime.of(2013, 7, 10, 2, 52, 49), zoneOffset);
System.out.println(odtGiven);
OffsetDateTime odtUtc = odtGiven.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odtUtc);
System.out.println(odtUtc.toLocalDateTime());
}
}
Output:
2013-07-10T02:52:49+12:00
2013-07-09T14:52:49Z
2013-07-09T14:52:49
Learn about the modern Date-Time API from Trail: Date Time.
Related
I receive this Date Time pattern from Server as a string.
Sa. 07.01.2023 16:39:15
Now i want to check if 1 minute is over.
Like if the gap between the current time and the time (received as a string) from server is
longer than a minute.
The time zone is in Europe. Like Austria.
Parse the given date-time string into a LocalDateTime.
Convert the obtained LocalDateTime into a ZonedDateTime by applying a ZoneId.
Get the current ZonedDateTime in the applied ZoneId.
Finally, find the minutes between the current ZonedDateTime and the ZonedDateTime obtained from the date-time string.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
class Main {
public static void main(String[] args) {
String strDateTime = "Sa. 07.01.2023 16:39:15";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE dd.MM.uuuu HH:mm:ss", Locale.GERMAN);
// Note: change the ZoneId as per your requirement
ZonedDateTime zdt = LocalDateTime.parse(strDateTime, parser)
.atZone(ZoneId.of("Europe/Vienna"));
System.out.println("Date-time received from the server: " + zdt);
ZonedDateTime now = ZonedDateTime.now(zdt.getZone());
System.out.println("Current date-time: " + now);
System.out.println(ChronoUnit.MINUTES.between(zdt, now) > 1);
}
}
Output from a sample run:
Date-time received from the server: 2023-01-07T16:39:15+01:00[Europe/Vienna]
Current date-time: 2023-01-07T17:33:04.140599+01:00[Europe/Vienna]
true
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
Incorporating the following valuable alternative solution suggested by Basil Bourque:
Might be more clear if you switch to Instant objects at the end.
Extract an Instant from your first ZonedDateTime, and change
ZonedDateTime now to Instant now.
class Main {
public static void main(String[] args) {
String strDateTime = "Sa. 07.01.2023 16:39:15";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE dd.MM.uuuu HH:mm:ss", Locale.GERMAN);
// Note: change the ZoneId as per your requirement
Instant instantParsed = LocalDateTime.parse(strDateTime, parser)
.atZone(ZoneId.of("Europe/Vienna"))
.toInstant();
System.out.println("Instant received from the server: " + instantParsed);
Instant instantNow = Instant.now();
System.out.println("Current instant: " + instantNow);
System.out.println(ChronoUnit.MINUTES.between(instantParsed, instantNow) > 1);
}
}
ONLINE DEMO
I have a UTC date-time like this (a String): 2022-11-22T17:15:00
And a ZoneID like this: "America/Tijuana"
Using java.time API, I want to get the actual datetime for that zone, which is: 2022-11-22T09:15:00 (the time is 09:15 instead of 17:15)
ZonedDateTime.toLocalDateTime() returns: 2022-11-22T17:15
ZonedDateTime.toString() returns:
2022-11-22T17:15-08:00[America/Tijuana]
None of the above gives me what I'm looking for.
This is my code:
ZoneId zonaID = ZoneId.of('America/Tijuana');
CharSequence dateUTC = "2022-11-22T17:15:00";
LocalDateTime dateTimeL = LocalDateTime.parse(dateUTC);
ZonedDateTime myZDT = ZonedDateTime.now();
ZonedDateTime myZDTFinal = myZDT.of(dateTimeL, zonaID);
System.out.println("using toLocalDateTime: " + myZDTFinal.toLocalDateTime());
System.out.println("using toString: " + myZDTFinal.toString());
I know that this might be a duplicated question but there's so many questions about date-times and I just haven't been able to figure out this.
Any help will be really appreciated.
You have to convert your date to UTC, then convert the convert this zone to your expected zone using withZoneSameInstant like this:
ZonedDateTime toUTCZone = ZonedDateTime.of(dateTimeL, ZoneOffset.UTC);
ZonedDateTime myZDTFinal = toUTCZone.withZoneSameInstant(zonaID);
Output
2022-11-22T09:15-08:00[America/Tijuana]
There can be many ways to achieve the result. A simple approach would be
Parse the given string into LocalDateTime.
Convert it into an OffsetDateTime at UTC using LocalDateTime#atOffset.
Use OffsetDateTime#atZoneSameInstant to convert the resulting OffsetDateTime into a ZonedDateTime at ZoneId.of("America/Tijuana").
Get LocalDateTime out of the resulting ZonedDateTime by using ZonedDateTime#toLocalDateTime.
If required, format this LocalDateTime into the desired string.
LocalDateTime
.parse("2022-11-22T17:15:00") // Parse the given date-time string into LocalDateTime
.atOffset(ZoneOffset.UTC) // Convert it into a ZonedDateTime at UTC
.atZoneSameInstant(ZoneId.of("America/Tijuana")) // Convert the result into a ZonedDateTime at another time-zome
.toLocalDateTime() // Get the LocalDateTime out of the ZonedDateTime
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH))); // If required
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDateTime ldtInTijuana = LocalDateTime.parse("2022-11-22T17:15:00")
.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.of("America/Tijuana"))
.toLocalDateTime();
System.out.println(ldtInTijuana);
// Custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
String formatted = ldtInTijuana.format(formatter);
System.out.println(formatted);
}
}
Output:
2022-11-22T09:15
2022-11-22T09:15:00
Note that LocalDateTime#toString removes second and fraction-of-second values if they are zero. Suppose you want to keep them (as you have posted in your question), you can use a DateTimeFormatter as shown above.
An alternate approach:
Alternatively, you can append Z at the end of your ISO 8601 formatted date-time string to enable Instant to parse it and then convert the Instant into a ZonedDateTime corresponding to the ZoneId.of("America/Tijuana") by using Instant#atZone. The symbol, Z refers to UTC in a date-time string.
The rest of the steps will remain the same.
Demo:
public class Main {
public static void main(String[] args) {
String text = "2022-11-22T17:15:00";
text = text + "Z"; // Z refers to UTC
Instant instant = Instant.parse(text);
LocalDateTime ldt = instant.atZone(ZoneId.of("America/Tijuana")).toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2022-11-22T09:15
Learn more about the modern Date-Time API from Trail: Date Time.
Given:
public static void main(String[] args) {
String dateString = "2018-07-30T13:36:17.820";
DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDate date = LocalDate.parse(dateString, DATE_TIME_FORMATTER);
ZonedDateTime zonedDateTime = date.atStartOfDay((ZoneOffset.UTC));
System.out.println(zonedDateTime);
}
And output:
2018-07-30T00:00Z
...what is the pattern to print seconds? Stupid question no doubt but driving me a little nuts
I need:
2018-07-30T00:00:00Z
I changed java.time.LocalDate to java.time.LocalDateTime, you need it if you want to show also the seconds.
package com.test;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class DateFormatter {
public static void main(String[] args) {
String dateString = "2018-07-30T13:36:17.820";
DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
LocalDateTime date = LocalDateTime.parse(dateString, DATE_TIME_FORMATTER);
ZonedDateTime zonedDateTime = date.atZone(ZoneOffset.UTC);
System.out.println(zonedDateTime);
}
}
Output is:
2018-07-30T13:36:17.820Z
LocalDate will keep just date. You need to parse LocalDateTime and convert to ZonedDateTime and you will have seconds as you expect.
var dateString = "2018-07-30T13:36:17.820";
var format = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
var localDate = LocalDateTime.parse(dateString, format);
var zone = ZoneId.of( "America/Montreal" );
var zonedDateTime = localDate.atZone(zone);
System.out.println(zonedDateTime);
You will have to go a few steps:
parse the String to a LocalDateTime because it contains date and time of day
extract the date only
create a ZonedDateTime out of that by adding the start of day (LocalTime.MIN = 00:00:00) and a ZoneOffset.UTC
This code may do:
public static void main(String[] args) {
String dateString = "2018-07-30T13:36:17.820";
// parse a LocalDateTime
LocalDateTime localDateTime = LocalDateTime.parse(dateString);
// extract the date part
LocalDate localDate = localDateTime.toLocalDate();
// make it a ZonedDateTime by applying a ZoneId
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDate, LocalTime.MIN, ZoneOffset.UTC);
// print the result
System.out.println(zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
}
Output is
2018-07-30T00:00:00Z
There are several ways to do it, this is just one of them and it just slightly differs from most of the other answers (and comments :-) ).
tl;dr
You have used the wrong things in the wrong places.
You do not need a DateTimeFormatter explicitly in order to parse 2018-07-30T13:36:17.820 because it's already in ISO 8601 format which is also the default format used by LocalDateTime#parse. Moreover, this string has date and time instead of just date; therefore, it makes more sense to parse it into LocalDateTime instead of LocalDate. You can always get LocalDate from LocalDateTime using LocalDateTime#toLocalDate.
The ZonedDateTime#toString uses the LocalDateTime#toString which in turn uses LocalTime#toString for the time part which omits second and fraction-of-second if they are zero. If you need a string with zero second and fraction-of-second, you will need to use a DateTimeFormatter.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String args[]) {
String dateString = "2018-07-30T13:36:17.820";
LocalDateTime localDateTime = LocalDateTime.parse(dateString);// You do not need a DateTimeFormatter here
ZonedDateTime zonedDateTime = localDateTime.toLocalDate().atStartOfDay(ZoneOffset.UTC);
// Print zonedDateTime.toString()
System.out.println(zonedDateTime);
// Custom format
final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
System.out.println(DATE_TIME_FORMATTER.format(zonedDateTime));
}
}
Output:
2018-07-30T00:00Z
2018-07-30T00:00:00.000
Learn more about the modern date-time API from Trail: Date Time.
I currently have a Date e.g. "2015-10-10T14:34:22Z". I need the year from the Date object for my new LocalDateTime object as this object will be set to that Date object year and have a specific month, day and time set (yyyy-06-15T17:00:00Z).
Taking the getYear() from Date has the 1900 issue.
I get the date via LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
Create another object to set the desired month and day
Create LocalDateTime object to set the time
I feel I am doing it a very long convuluted way and would like to ask if there are any other shorter and better alternatives.
EDIT:
Are there are any other shorter and better alternatives?
Since your date-time string has timezone offset information. So, you can parse it to an OffsetDateTime object and then get the year from it.
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
public class Main {
public static void main(String[] args) {
String strDateTime = "2015-10-10T14:34:22Z";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
System.out.println(odt);
System.out.println(odt.getYear());
// If you want to get LocalDateTime from OffsetDateTime
LocalDateTime ldt = odt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2015-10-10T14:34:22Z
2015
2015-10-10T14:34:22
Note that Z in the date-time string stands for Zulu date-time and specifies a timezone offset of +00:00 hours or date-time at UTC.
Taking the getYear() from Date has the 1900 issue.
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. I suggest you should stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Converting from legacy API to the modern API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
String strDateTime = "2015-10-10T14:34:22Z";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date date = sdf.parse(strDateTime);
Instant instant = date.toInstant();
OffsetDateTime odt = instant.atOffset(ZoneOffset.UTC);
System.out.println(odt);
System.out.println(odt.getYear());
// If you want to get LocalDateTime from OffsetDateTime
LocalDateTime ldt = odt.toLocalDateTime();
System.out.println(ldt);
}
}
Output:
2015-10-10T14:34:22Z
2015
2015-10-10T14:34:22
Note: If you want to convert the Instant into ZonedDateTime at UTC, you can do it as follows:
ZonedDateTime zdt = instant.atZone(ZoneOffset.UTC);
or the following:
ZonedDateTime zdt = instant.atZone(ZoneId.of("Etc/UTC"));
Note that the three-letter name for a ZoneId is error-prone i.e. avoid using something like ZoneId.of("UTC").
What is wrong with your code:
You are using .atZone(ZoneId.systemDefault()) which is converting the object of Instant to an object of ZonedDateTime with your JVM's timezone. You have to use .atOffset(ZoneOffset.UTC) as shown above to keep the date-time with the same timezone offset (i.e. +00:00 hours or date-time at UTC) which is there in the date-time string.
try this :
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX");
try {
String s = "2015-10-10T14:34:22+02";
s = s.replaceAll("T", " ");
Date d = df.parse(s);
Calendar cl = Calendar.getInstance();
cl.setTime(d);
System.out.println(cl.getTime());
System.out.println("year : " + cl.get(Calendar.YEAR));
} catch (ParseException e) {
System.err.println(e);
}
output
Sat Oct 10 13:34:22 GMT+01:00 2015
year : 2015
Maybe this approach could help:
import java.text.ParseException;
import java.time.*;
import java.util.Date;
public class ConvertDate {
public static void main(String[] args) throws ParseException {
Date date = new Date();
LocalDateTime localDateTime = date.toInstant().atOffset(ZoneOffset.UTC).toLocalDateTime();
System.out.println(localDateTime);
System.out.println(localDateTime.getYear());
}
}
Time zone is crucial
You need to decide in which time zone you want the year. New Year doesn’t happen at one point in time across the globe, but over a span of about 26 hours. So if your date string is within a day or so of New Year, your result could be off by a year if you don’t pick the correct time zone. For example:
ZoneId zone = ZoneId.of("America/Louisville");
// The year in the following object does not matter
ZonedDateTime fixedTimeOfYear = ZonedDateTime.of(2020, 6, 15, 17, 0, 0, 0, zone);
String inputString = "2015-01-01T01:02:03Z";
OffsetDateTime input = OffsetDateTime.parse(inputString);
int year = input.atZoneSameInstant(zone).getYear();
System.out.format("Year in %s is %d%n", zone, year);
ZonedDateTime desiredTime = fixedTimeOfYear.withYear(year);
System.out.println("Result: " + desiredTime);
Output from this snippet is:
Year in America/Louisville is 2014
Result: 2014-06-15T17:00-04:00[America/Louisville]
You notice that even though the year in the string is 2015, it is still only 2014 in the time zone that I chose for the demonstration, so the resulting date and time are in 2014. The example was picked to demonstrate my point.
Don’t use LocalDateTime
The frequent use of LocalDateTime that you mention in a comment is a misunderstanding. For a date and time in a known time zone in 2015, for example, LocalDateTime is the wrong class to use. Use ZonedDateTime or at least OffsetDateTime so we know what we are talking about. These classes have the advantages that they keep track of time zone or offset themselves, and that they define an unambiguous point in time. LocalDateTime does nothing of this.
My date-time format string is : yyyy-MM-dd'T'HH:mm:ss.SSSZ
I am using DateTimeFormatter from Joda Time to print my date in the above mentioned format.
Now, consider the date as
2016/04/01 23:00:00
then it should have printed
2016-04-01T23:00:00.000Z
But, it prints
2016-04-01T23:00:00.000+0200
Please help me in getting the date printed in the same format as specified in the string format.
2016-04-01T23:00:00.000Z != 2016-04-01T23:00:00.000+0200
Here is what Basil Bourque has commented on the wrong answer:
No, no, no. All you have done is append text, creating a falsity. If
your date-time represents a moment in a time zone that is two hours
ahead of UTC such as Europe/Helsinki, and you slap a Z on the end
which says Zulu and means UTC, you are now telling a lie, representing
value that is off by two hours. This is like replacing the dollar sign
in a price with a Euro currency symbol but failing to change the
number.
Just to illustrate what he has mentioned:
£100 != $100
The Z in 2016-04-01T23:00:00.000Z is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours). The same moment will be presented in different timezones with different values e.g.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
Instant instant = Instant.parse("2016-04-01T23:00:00.000Z");
ZonedDateTime zdtNewYork = instant.atZone(ZoneId.of("America/New_York"));
ZonedDateTime zdtIndia = instant.atZone(ZoneId.of("Asia/Kolkata"));
ZonedDateTime zdtNepal = instant.atZone(ZoneId.of("Asia/Kathmandu"));
System.out.println(zdtNewYork);
System.out.println(zdtIndia);
System.out.println(zdtNepal);
// Or at a fixed timezone offset of +02:00 hours
OffsetDateTime odtWithTwoHoursOffset = instant.atOffset(ZoneOffset.of("+02:00"));
System.out.println(odtWithTwoHoursOffset);
}
}
Output:
2016-04-01T19:00-04:00[America/New_York]
2016-04-02T04:30+05:30[Asia/Kolkata]
2016-04-02T04:45+05:45[Asia/Kathmandu]
2016-04-02T01:00+02:00
To understand this concept a bit further, try converting a date-time from one timezone to another e.g. I have shown a conversion of a New York date-time into UTC. I have shown another conversion of a date-time with a timezone offset of +02:00 hours into UTC.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
// #######Example of converting a date-time from one timezone to another#####
ZonedDateTime zdtNewYork = ZonedDateTime.parse("2016-04-01T19:00-04:00[America/New_York]");
Instant instant = zdtNewYork.toInstant();
System.out.println(instant);
// Or as ZonedDateTime
ZonedDateTime zdtUtc = zdtNewYork.withZoneSameInstant(ZoneId.of("Etc/UTC"));
System.out.println(zdtUtc);
// Alternatively, this can be obtained from instant
zdtUtc = instant.atZone(ZoneId.of("Etc/UTC"));
System.out.println(zdtUtc);
// ###########################################################################
System.out.println();
// #####Example of converting a date-time at a fixed timezone offset to UTC###
OffsetDateTime odtNewYork = OffsetDateTime.parse("2016-04-02T01:00+02:00");
instant = odtNewYork.toInstant();
System.out.println(instant);
// Alternatively
OffsetDateTime odtUtc = odtNewYork.withOffsetSameInstant(ZoneOffset.UTC);
System.out.println(odtUtc);
// Alternatively,
odtUtc = instant.atOffset(ZoneOffset.UTC);
System.out.println(odtUtc);
// ###########################################################################
}
}
Output:
2016-04-01T23:00:00Z
2016-04-01T23:00Z[Etc/UTC]
2016-04-01T23:00Z[Etc/UTC]
2016-04-01T23:00:00Z
2016-04-01T23:00Z
2016-04-01T23:00Z
According https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html Z has special meaning:
Z zone-offset
If you want to escape Z quote Z with ':
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
For example:
java.time.LocalDateTime date = java.time.LocalDateTime.now();
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
java.lang.String text = date.format(formatter);
System.out.println(text);
prints
2016-06-11T18:39:41.962Z