Domanda

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;
    }
È stato utile?

Soluzione

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));

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top