Convert WallClock Time from one timezone to another timezone - java

I want to convert wall clock time time from one TZ to another without doing OFFSET math myself.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
String d = sdf.format(new Date());
System.out.println(d);
sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
String d1 = sdf.format(new Date());
System.out.println(d1);
Output:
2018.07.09 13:43:30 PDT
2018.07.09 16:43:30 EDT
Desired Output
2018.07.09 13:43:30 PDT
2018.07.09 13:43:30 EDT
How can I get the desired output?

java.time and ThreeTen Backport
DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss z", Locale.US);
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("America/Los_Angeles"));
String d = zdt.format(formatter);
System.out.println(d);
zdt = zdt.withZoneSameLocal(ZoneId.of("America/New_York"));
String d1 = zdt.format(formatter);
System.out.println(d1);
Output when I ran the code just now:
2018.07.10 04:30:20 PDT
2018.07.10 04:30:20 EDT
The ZonedDateTime class that you mentioned in a comment has your desired conversion built in, in its withZoneSameLocal method. This returns the same wall clock time in the specified time zone.
As of now, we use Java 7. We have not upgraded our infra to java 8…
No big problem. java.time and its ZonedDateTime work nicely on Java 7. They just require at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Related

2021-04-05T16:25:45.000+00:00 Time stamp change in SimpleDateFormat("yyyy-MM-dd hh:mm:ss a")

My Code
String date = "2021-04-05T16:25:45.000+00:00";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
Date parsedDate = null;
try {
parsedDate = inputFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = outputFormat.format(parsedDate);
Error:
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference
java.time through desugaring
Consider using java.time, the modern Java date and time API, for your date and time work. Use for example this output formatter:
private static final DateTimeFormatter OUTPUT_FORMATTER
= DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a", Locale.forLanguageTag("en-IN"));
With it do:
String date = "2021-04-05T16:25:45.000+00:00";
OffsetDateTime dateTime = OffsetDateTime.parse(date);
String formattedDate = dateTime.format(OUTPUT_FORMATTER);
System.out.println(formattedDate);
Output:
2021-04-05 04:25:45 PM
You may use a different locale for the output formatter as appropriate for your requirements. The choice of locale determines which strings are used for AM and PM.
I am exploiting the fact that the string that you have got is in ISO 8601 format. offsetDateTime parses this format as its default, that is, without any explicit formatter.
What went wrong in your code?
You tried using a format pattern string of yyyy-MM-dd'T'HH:mm:ss.SSS'Z' for a date string of 2021-04-05T16:25:45.000+00:00. The 'Z' in single quotes in the format pattern string means that your date string must end in a literal Z. When instead it ended in +00:00, parsing failed with a ParseException. If you didn’t see the output from e.printStackTrace(); in your code, you have got a serious flaw in your project setup that you should fix before worrying about how to parse the date string. In any case, since parsing failed, parsedDate kept its initial value of null, which caused outputFormat.format(parsedDate) to throw the NullPointerException that you did see.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601

How to generate localized datetime from "20201023T200457Z" and from "EEE MMM dd HH:mm:ss zzz yyyy"? [duplicate]

This question already has answers here:
Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST
(9 answers)
parsing date/time to localtimezone
(2 answers)
Closed 2 years ago.
I have this start datetime: "20201023T200457Z" (it seem to be UTC0000)
how can I convert/generate it with this "yyyyMMdd HH:mm:ss" pattern in local time on a mobile?
I get this result: Fri Oct 23 20:04:57 GMT+02:00 2020
with this code:
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.getDefault());
Date startGMTInput = df.parse(start);
Log.e(TAG, "start: " + startGMTInput.toString());// -> Fri Oct 23 20:04:57 GMT+02:00 2020
But my target is to get: 2020-10-23 22:04:57 //because I'm in GMT+2 timezone
java.time either through desugaring or ThreeTenABP
Consider using java.time, the modern Java date and time API, for your date and time work. Let’s first define the formatters we need:
private static final DateTimeFormatter inputFormatter
= DateTimeFormatter.ofPattern("uuuuMMdd'T'HHmmssX");
private static final DateTimeFormatter outputFormatter
= DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss");
( DateTimeFormatter is thread-safe, so we can safely declare them static.) Do the time zone conversion explicitly:
String startString = "20201023T200457Z";
Instant start = inputFormatter.parse(startString, Instant.FROM);
String target = start.atZone(ZoneId.systemDefault()).format(outputFormatter);
System.out.println(target);
Output in my time zone (currently at offset +02:00 like yours):
20201023 22:04:57
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in. Only in this case use the method reference Instant::from instead of the constant Instant.FROM.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On older Android either use desugaring or the Android edition of ThreeTen Backport. It’s called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java 8+ APIs available through desugaring
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Set your timezone to GMT+2 before any date operations.
isoFormat.setTimeZone(TimeZone.getTimeZone("GMT+2"));

Instant.now equivalent to java.util.Date or Java 7

I have a system using Java 7 and I need to generate a date equivalente to Instant.now (Java 8).
For example, Instant.now().toString() generate a date like that:
"2018-12-19T12:32:46.816Z"
Using java.util.Date I have this date: "2018-12-19T10:38:13.892"
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String text = sdf.format(date);
System.out.println(text);
I don't know if I can simply concatenate a "Z" at the end of this date.
Without "Z" another system that parse this date using Instant.parse throws the error:
java.time.format.DateTimeParseException: Text
'2018-12-19T10:38:13.892' could not be parsed at index 23
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1988)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1890)
at java.base/java.time.Instant.parse(Instant.java:395)
Z means UTC time zone, you can set the time zone to UTC and append Z mannually:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
ThreeTen Backport
java.time, the modern Java date and time API, has been backported. So just do as you would in Java 8:
String text = Instant.now().toString();
Running just now I got:
2018-12-19T13:37:37.186Z
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
The outdated SimpleDateFormat
If you don’t want to rely on an external dependency just until you move to Java 8 or higher, the (most) correct solution is this combination of pieces from the two other answers (one of them now deleted):
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXX");
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String text = sdf.format(System.currentTimeMillis());
2018-12-19T13:37:37.285Z
It doesn’t always give the exact same string as Instant.toString, but it will give a string that Instant can parse in the other system. While Instant.toString() only prints as many decimals as necessary, the above SimpleDateFormat will print three decimals also when some of them are 0.
When the time zone of the formatter is UTC, format pattern letter (uppercase) X will print Z as “time zone” (really just an offset).
Links
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Oracle tutorial: Date Time explaining how to use java.time.

Change DateFormat in Android Studio

I have data from API, the data is date with format "2018-07-09". How to change the format to Monday, July 9 , 2018 in android studio?
You can parse string to object them format it with DateTimeFormatter:
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMMM d, yyyy", Locale.ENGLISH);
System.out.println(formatter.format(parser.parse( "2018-07-09"))); // Monday, July 9, 2018
SimpleDateFormat fromApi = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat myFormat = new SimpleDateFormat("EEEE, MMMM d, yyyy");
try {
String reformattedStr = myFormat.format(fromApi.parse(inputString));
} catch (ParseException e) {
e.printStackTrace();
}
See oracle doc for more understanding.
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.FULL)
.withLocale(Locale.US);
LocalDate date = LocalDate.parse("2018-07-09");
String formattedDate = date.format(dateFormatter);
System.out.println(formattedDate);
This prints:
Monday, July 9, 2018
Messages:
The date string you get from the API, 2018-07-09, is in ISO 8601 format. LocalDate from java.time, the modern Java date and time API, parses this format as its default, that is, without any explicit formatter. So don’t go to the trouble of creating one.
For display to the user use the built-in formats. You get them from the DateTimeFormatter.ofLocalizedXxxx methods and may adapt them to the user’s locale as shown in the above code.
You tagged your question simpledateformat. The SimpleDateFormat class is long outdated and notoriously troublesome, so please avoid it. java.time is much nicer to work with.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601

String Date + Time to Date Object Java

I am trying to convert a string "8/2/2018 04:25 AM" into a date object but it seems to be converting it wrong making it output a completely wrong date and time when I do a date.toString(). Note - I do not care about the date.toString() format, I just need it to be the same date and time
Here is my code,
String timestampString = dateText.getText().toString() + " " + timeText.getText().toString();
try {
Date timestamp2 = new SimpleDateFormat("dd/MM/yyyy hh:mm a").parse(timestampString);
Log.d("TIME", timestamp2.toString());
} catch (ParseException e) {Log.d("TAG", e)}
Here is the output:
D/TIME: Wed Feb 07 23:25:00 EST 2018
if anyone could lead me in the right direction, it is greatly appreciated.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/uuuu");
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
LocalDate date = LocalDate.parse(dateText.getText(), dateFormatter);
LocalTime time = LocalTime.parse(timeText.getText(), timeFormatter);
LocalDateTime dateTime = date.atTime(time);
Log.d("TIME", dateTime.toString());
Prints:
D/TIME: 2018-02-08T04:25
I am using and recommending java.time, the modern Java date and time API.The Date class that you were using is long outdated, SimpleDateFormat is too and also notoriously troublesome. Avoid those if you can. java.time is so much nicer to work with. And offers the LocalXx classes that don’t have time zones, which guarantees to guard you against time zone issues. That said, you may want to convert your date-time into a ZonedDateTime in a time zone of your choice to make it an unambiguous point in time.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.timeto Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

Categories