33

I have seen this question asked multiple times and none of the answers seem to be what i need.

I have a long type variable which has an epoch time stored in it.

What i want to do is convert it to a String

for example if the epoch time stored was for today the final string would read:

17/03/2012

How would i to this?

nexus490
  • 797
  • 5
  • 11
  • 21

10 Answers10

44

Look into SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.format(new Date(myTimeAsLong));
Shivansh
  • 906
  • 12
  • 25
Reinard
  • 3,624
  • 10
  • 43
  • 61
  • 1
    Ive got that to print out a string in the correct format but it prints out the incorrect date it gives todays date as 16/00/1970. The Long used was 1332026487. – nexus490 Mar 17 '12 at 23:22
  • It's because you might have to play around with the parameter you pass in the constructor. You can find all display possibilities in the Jav API – Reinard Mar 17 '12 at 23:28
  • 9
    This answer: is printing the *minute* instead of *month*; ignores the choice of culture (which is very important); ignores the choice of time zone (which is incredibly important). You've really got to think about these things - it's no help (IMO) to just ignore them. – Jon Skeet Mar 17 '12 at 23:39
  • 5
    The Long provided by @nexus490 seems to be in seconds (i.e. the "real" epoch format), while the Java implementation of the Date class would need the time in milliseconds. Try multiplying your Long by 1000 and it should work. Besides that, +1000 for Jon Skeet's comment. – dbm Jan 30 '13 at 19:46
32

You'd create a Date from the long - that's easy:

Date date = new Date(epochTime);

Note that epochTime here ought to be in milliseconds since the epoch - if you've got seconds since the epoch, multiply by 1000.

Then you'd create a SimpleDateFormat specifying the relevant pattern, culture and time zone. For example:

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
format.setTimeZone(...);

Then use that to format the date to a string:

String text = format.format(date);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    What would i put for the Timezone argument? – nexus490 Mar 17 '12 at 23:15
  • @nexus490: Well what time zone do you want to represent the value in? For example, in an hour it will be 18/03/2012 in *my* time zone, but in the US it will still be 17/03/2012, for the same number of milliseconds since the epoch. What would the right answer be? That's something only *you* know, as you know your application requirements (hopefully). Maybe you want UTC. Maybe you want the system local time zone. Maybe you want the user's home time zone. – Jon Skeet Mar 17 '12 at 23:40
  • Thank for for stressing this: "if you've got **seconds** since the epoch, multiply by **1000**." – Javad Jan 10 '15 at 21:42
  • This is how you'd get milliseconds: `long now = Instant.now().toEpochMilli();` Also, `import java.time.Instant;` and `import java.text.SimpleDateFormat;` I'm a Java noob and I had to look elsewhere for the full picture. For the sake of being complete, I'm adding this here. – harperville Feb 19 '20 at 17:19
21
Date date = new Date(String); 

this is deprecated.

solution

  Date date = new Date(1406178443 * 1000L);
  DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
  String formatted = format.format(date);

make sure multiply by 1000L

Damith Ganegoda
  • 4,100
  • 6
  • 37
  • 46
5

If the method should be portable, better use the default (local time) TimeZone.getDefault():

String epochToIso8601(long time) {
    String format = "yyyy-MM-dd HH:mm:ss";
    SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
    sdf.setTimeZone(TimeZone.getDefault());
    return sdf.format(new Date(time * 1000));
}
Martin Zeitler
  • 1
  • 19
  • 155
  • 216
3

try this

Date date = new Date(1476126532838L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
format.setTimeZone(TimeZone.getTimeZone("Asia/Colombo"));//your zone
formatted = format.format(date);
System.out.println(formatted);
Charitha Goonewardena
  • 4,418
  • 2
  • 36
  • 38
2

Joda-Time

If by epoch time you meant a count of milliseconds since first moment of 1970 in UTC, then here is some example code using the Joda-Time library…

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = new DateTime( yourMilliseconds, timeZone );
String output = DateTimeFormat.forStyle( "S-" ).withLocale( Locale.CANADA_FRENCH ).print( dateTime );

Other Epochs

That definition of epoch is common because of its use within Unix. But be aware that at least a couple dozen epoch definitions are used by various computer systems.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

Try this...

sample Epoch timestamp is 1414492391238

Method:

public static String GetHumanReadableDate(long epochSec, String dateFormatStr) {
    Date date = new Date(epochSec * 1000);
    SimpleDateFormat format = new SimpleDateFormat(dateFormatStr,
            Locale.getDefault());
    return format.format(date);
}

Usability:

long timestamp = Long.parseLong(engTime) / 1000;
String engTime_ = GetHumanReadableDate(timestamp, "dd-MM-yyyy HH:mm:ss aa");

Result:

28-10-2014 16:03:11 pm

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Silambarasan Poonguti
  • 9,386
  • 4
  • 45
  • 38
  • 1
    3 problems with this answer. This answer ignores the crucial issue of time zone. This answer uses a different format than requested in the Question. And this answer essentially duplicates three other answers posted months ago. I don't see any value-add here. – Basil Bourque Oct 28 '14 at 23:17
1

Time for someone to provide the modern answer (valid and recommended since 2014).

java.time

    DateTimeFormatter formatter = DateTimeFormatter
            .ofLocalizedDateTime(FormatStyle.LONG).withLocale(Locale.US);

    String facebookTime = "1548410106047";
    long fbt = Long.parseLong(facebookTime);
    ZonedDateTime dateTime = Instant.ofEpochMilli(fbt).atZone(ZoneId.of("America/Indiana/Knox"));
    System.out.println(dateTime.format(formatter));

The output is:

January 25, 2019 at 3:55:06 AM CST

If you wanted only the date and in a shorter format, use for example

    DateTimeFormatter formatter = DateTimeFormatter
            .ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.US);

1/25/19

Note how the snippet allows you to specify time zone, language (locale) and how long or short of a format you want.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
0

You need to be aware that epoch time in java is in milliseconds, while what you are converting may be in seconds. Ensure that both sides of the conversions are in milliseconds, and then you can fetch the date parameters from the Date object.

Ajibola
  • 1,218
  • 16
  • 28
-1

ArLiteDTMConv Utility help converting EPOUCH-UNIX Date-Time values, Form EPOUCH-UNIX-To-Date-format and Vise-Versa. You can set the result to a variable and then use the variable in your script or when passing as parameter or introduce in any DB criteria for both Window and Linux. (Download a zip file on this link)

Ali Musa
  • 1
  • 1