String Date + Time to Date Object Java - 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.

Related

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

Parse UTC time format into readable datetime in android

I have an UTC datetime in the format 2019-12-06T06:04:50.022461Z I want to convert into readable datetime in the format dd-mm-yyyy hh:mm:ss. I am not able to convert in the particular format. Any help will be highly appreciated. Thanks
java.time and ThreeTenABP
I am assuming that you want to display the time in your user’s time zone. As you said already, your string is in UTC, and very few users will be happy to read the time in UTC.
DateTimeFormatter readableFormatter = DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss");
String originalString = "2019-12-06T06:04:50.022461Z";
String readableString = Instant.parse(originalString)
.atZone(ZoneId.systemDefault())
.format(readableFormatter);
System.out.println(readableString);
For the sake of the example I ran this code in America/Sitka time zone. Output was:
05-12-2019 21:04:50
If you did want to display the time in UTC as in the original string:
String readableString = OffsetDateTime.parse(originalString)
.format(readableFormatter);
06-12-2019 06:04:50
Don’t go with the classes SimpleDateFormat, TimeZone and Calendar used in the currently accepted answer. They are all poorly designed, SimpleDateFormat in particular is a notorious troublemaker and also cannot parse 6 decimals on the seconds as in your string. Those three classes are also all long outdated. Instead I am using java.time, the modern Java date and time API. It is so much nicer to work with. The code is not only shorter, I think that you will also find it clearer to read (either immediately or when you get used to the fluent style).
I am exploiting the fact that your original string is in ISO 8601 format. The classes of java.time parse ISO 8601 format as their default, that is, without any explicit formatter.
For the vast majority of purposes you shold not want to convert from one string format to another, though. Inside your program keep your date and time as an Instant or other proper date/time object. only convert to a string when a string is needed in the interface.
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 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.time to 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
You can use SimpleDateFormat to format the date. Check below:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(sdf.parse("2019-12-06T06:04:50.022461Z"));
} catch (Exception ex) {
ex.printStackTrace();
}
SimpleDateFormat returnFormat = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
returnFormat.format(calendar.getTime());
You can try this in java 8
String dateString = "2019-12-06T06:04:50.022461Z";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
TemporalAccessor date = fmt.parse(dateString);
Instant time = Instant.from(date);
DateTimeFormatter fmtOut = DateTimeFormatter.ofPattern("dd-mm-yyyy hh:mm:ss").withZone(ZoneOffset.UTC);
String newDateString = fmtOut.format(time);

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.

Convert WallClock Time from one timezone to another timezone

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.

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

Categories