16

I'm trying to convert a millisecond time (milliseconds since Jan 1 1970) to a time in UTC in Java. I've seen a lot of other questions that utilize SimpleDateFormat to change the timezone, but I'm not sure how to get the time into a SimpleDateFormat, so far I've only figured out how to get it into a string or a date.

So for instance if my initial time value is 1427723278405, I can get that to Mon Mar 30 09:48:45 EDT using either String date = new SimpleDateFormat("MMM dd hh:mm:ss z yyyy", Locale.ENGLISH).format(new Date (epoch)); or Date d = new Date(epoch); but whenever I try to change it to a SimpleDateFormat to do something like this I encounter issues because I'm not sure of a way to convert the Date or String to a DateFormat and change the timezone.

If anyone has a way to do this I would greatly appreciate the help, thanks!

Community
  • 1
  • 1
kpb6756
  • 241
  • 1
  • 4
  • 11

3 Answers3

35

java.time option

You can use the new java.time package built into Java 8 and later.

You can create a ZonedDateTime corresponding to that instant in time in UTC timezone:

ZonedDateTime utc = Instant.ofEpochMilli(1427723278405L).atZone(ZoneOffset.UTC);
System.out.println(utc);

You can also use a DateTimeFormatter if you need a different format, for example:

System.out.println( DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss").format(utc));
assylias
  • 321,522
  • 82
  • 660
  • 783
17

Try below..

package com.example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TestClient {

    /**
     * @param args
     */
    public static void main(String[] args) {
        long time = 1427723278405L;
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(sdf.format(new Date(time)));

    }

}
Arsen Davtyan
  • 1,891
  • 8
  • 23
  • 40
Pavan Kumar K
  • 1,360
  • 9
  • 11
2

You May check this..

Calendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(1427723278405L);

    DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");

    formatter.setCalendar(calendar);

    System.out.println(formatter.format(calendar.getTime()));

    formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));

    System.out.println(formatter.format(calendar.getTime()));
Tariq
  • 56
  • 2