Search code examples
javadatetimesimpledateformatdatetime-conversion

Convert from Millisecond to String of Date


I try to convert from Milliseconds to string of date. However, the result is not correct as my expected.

The input is milliseconds (Ex: 1508206600485)

My time zone is UTC +10:00

------Expected-------------------------------------------- Actual------

01:32 (PM) 17/10/2017--------------------------------02:32 (PM) 17/10/2017

Here is the method of that

public static String getDate(long milliSeconds) {
    SimpleDateFormat formatter = new SimpleDateFormat("hh:mm dd/MM/yyyy");
    String dateString = formatter.format(new Date(milliSeconds));
    return dateString;
}

Solution

  • Good you found a solution, I just like to add an approach with Java 8 new java.time API. The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and it's strongly recommended to switch to the new API if possible.

    If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, you'll also need the ThreeTenABP (more on how to use it here).

    The code below works for both. The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.

    To convert the millis value to a specific timezone, you can use the Instant class, then use a ZoneId to convert to a timezone, creating a ZonedDateTime. Then you use a DateTimeFormatter to format it:

    // convert millis value to a timezone
    Instant instant = Instant.ofEpochMilli(1508206600485L);
    ZonedDateTime z = instant.atZone(ZoneId.of("Australia/Sydney"));
    // format it
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm dd/MM/yyyy");
    System.out.println(fmt.format(z)); // 01:16 17/10/2017
    

    The output is:

    01:16 17/10/2017

    Note that I used hh for the hours. According to javadoc, this lettern represents the clock-hour-of-am-pm field (values from 1 to 12), so without the AM/PM indicator, it can be ambiguous. Maybe you want to add AM/PM field (adding the letter a to the format pattern), or change the hours to HH (hour-of-day, with values from 0 to 23).

    Also note that the actual value of the ZonedDateTime is 2017-10-17T13:16:40.485+11:00 (01:16 PM), because in October 17th 2017, Sydney is in Daylight Saving Time, so the actual offset is +11:00.