1

I am getting an epoch String from my DB which looks something like this : 1391328000000

I am having a hard time trying to convert it to Java Date.

I tried the following :

private String buildDate(String dateString){
        System.out.println("dateString " + dateString);

        DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
        String formatted = format.format(Integer.parseInt(dateString));

        return formatted;
    }
Pi Horse
  • 2,350
  • 8
  • 30
  • 51
  • 2
    Well what date is that meant to represent? And do you really have to get it as a string rather than as a number? (I suspect it's actually milliseconds since the unix epoch.) – Jon Skeet Dec 05 '13 at 22:06

2 Answers2

6

I think you're overthinking about the DateFormat. If I want to simply obtain a Date instance, what I would try is the following:

Date d = new Date(Long.parseLong(dateString));
Andrei Nicusan
  • 4,555
  • 1
  • 23
  • 36
  • Please note the epoch string the asker used as an example is in Milliseconds. If you are workign with epoch in seconds, you should: new Date(Long.parseLong(dateString) * 1000) – Ezequiel Adrian Oct 08 '21 at 16:51
3

You need to turn it into a java.util.Date object in order for SimpleDateFormat to handle it. Also, a value like what you quoted needs to be parsed as a long, as it is too large for an int.

That is, change the line where you set formatted to be:

String formatted = format.format(new Date(Long.parseLong(dateString)));

As an aside, if the project you're working on can handle an extra external dependency, switch date/time handling over to the joda library. The stuff in java.util (that is, Date and Calendar) rapidly becomes painful and error-prone to work with.

Daniel Martin
  • 23,083
  • 6
  • 50
  • 70
  • 2
    You don't actually have to make a Date with SimpleDateFormat. The implementation of `java.text.Format#format(Object obj)` is friendly enough to convert Number to Date for you. – Affe Dec 05 '13 at 22:16