I found that this gives a wrong date. but how i can not solve it. please someone help me. I am new in android Development. Thanks in advance;
String timestamp = \"15
I recommend you use java.time, the modern Java date and time API, for your date and time work.
DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS)
.toFormatter();
DateTimeFormatter targetFormatter
= DateTimeFormatter.ofPattern("d MMM 'at' h:mm a z", Locale.ENGLISH);
String timestamp = "1538970640";
ZonedDateTime dateTime = timestampFormatter.parse(timestamp, Instant.FROM)
.atZone(ZoneId.systemDefault());
String dateString = dateTime.format(targetFormatter);
System.out.println(dateString);
Output is (when time zone is set to GMT+06:00, which by the way is not a true time zone):
8 Oct at 9:50 AM GMT+06:00
I am not very happy about converting date and time from one string format to another, though. In your app you should not handle date and time as strings but as proper date and time objects, for example Instant
or ZonedDateTime
. When you get a string from somewhere (a server?), parse it into a date-time object first thing. Only when you need to give string output, for example to the user, format your date and time into a string in the user’s time zone.
That said, java.time performs your conversion with just two formatters. No need to parse into a low-level long
first.
Two more points:
Locale.ENGLISH
might be appropriate. You decide.8 Oct at 9:50 AM GMT+06:00
, use just one d
for day of month and one h
for clock hour. Two digits will still be printed if the numbers go over 9, for example 10 Oct at 11:50 AM GMT+06:00
.Your number, 1538970640 (10 digits), denotes seconds since the epoch. This is the classical definition of a Unix timestamp. The Date
constructor that you used expects milliseconds since the epoch. This is typical for the outdated Java date and time classes and methods. These years milliseconds since the epoch are typically 13 digits. As you can see, the modern Java date and time classes have better support for seconds here.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
Instant.FROM
use the method references Instant::from
.org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).