Skip to content Skip to sidebar Skip to footer

How To Convert Timestamp Into Date Format In Java

I have a time stamp like this(form a json response) : '/Date(1479974400000-0800)/' I'm trying this function to convert time stamp into date: public String getDate() { Calendar

Solution 1:

Edit: parse directly into OffsetDateTime

Java can directly parse your string into an OffsetDateTime. Use this formatter:

privatestaticfinalDateTimeFormatterjsonTimestampFormatter=newDateTimeFormatterBuilder()
        .appendLiteral("/Date(")
        .appendValue(ChronoField.INSTANT_SECONDS)
        .appendValue(ChronoField.MILLI_OF_SECOND, 3)
        .appendOffset("+HHMM", "Z")
        .appendLiteral(")/")
        .toFormatter();

Then just do:

Stringtime="/Date(1479974400000-0800)/";
    OffsetDateTimeodt= OffsetDateTime.parse(time, jsonTimestampFormatter);
    System.out.println(odt);

Output is:

2016-11-24T00:00-08:00

In your string 1479974400000 is a count of milliseconds since the epoch of Jan 1, 1970 at 00:00 UTC, and -0800 is an offset of -8 hours 0 minutes from UTC (corresponding for example to Pacific Standard Time). To parse the milliseconds we need to parse the seconds since the epoch (all digits except the last three) and then the millisecond of second (the last three digits). By specifying the width of the milliseconds field as 3 Java does this. For it to work it requires that the number is at least 4 digits and not negative, that is not within the first 999 milliseconds after the epoch or earlier.

I specified Z for offset zero, I don’t know if you may ever receive this. An offset of +0000 for zero can still be parsed too.

Original answer

First I want to make sure the timestamp I have really lives up to the format I expect. I want to make sure if one day it doesn’t, I don’t just pretend and the user will get incorrect results without knowing they are incorrect. So for parsing the timestamp string, since I didn’t find a date-time format that would accept milliseconds since the epoch, I used a regular expression:

Stringtime="/Date(1479974400000-0800)/";
    Patternpat= Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
    Matcherm= pat.matcher(time);
    if (m.matches()) {
        Instanti= Instant.ofEpochMilli(Long.parseLong(m.group(1)));
        System.out.println(i);
    }

This prints:

2016-11-24T08:00:00Z

If you want an old-fashioned java.util.Date:

        System.out.println(Date.from(i));

On my computer it prints

ThuNov2409:00:00CET2016

This will depend on your time zone.

It is not clear to me whether you need to use the zone offset and for what purpose. You may retrieve it from the matcher like this:

        ZoneOffset zo = ZoneOffset.of(m.group(2));
        System.out.println(zo);

This prints:

-08:00

The zone offset can be used with other time classes, like for instance OffsetDateTime. For example:

        OffsetDateTime odt = OffsetDateTime.ofInstant(i, zo);
        System.out.println(odt);

I hesitate to mention this, though, because I cannot know whether it is what you need. In any case, it prints:

2016-11-24T00:00-08:00

Solution 2:

If by date you mean Date instance, then you can do this:

newDate(Long.parseLong("\/Date(1479974400000-0800)\/".substring(7, 20)));

Solution 3:

I assume this info in holding the String representing an Epoch and a TimeZone

"/Date(1479974400000-0800)/"

you need to get rid off the all the not necessary parts and keeping only the 1479974400000-0800

then the epoch is 1479974400000 and I guess the Timezone is 0800

then do:

String[] allTimeInfo = "1310928623-0800".split("-");
DateFormat timeZoneFormat =new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("Etc/GMT-8"));
Datetime=new java.util.Date(Long.parseLong(allTimeInfo[0]));
System.out.println(time);
System.out.println(timeZoneFormat.format(time));

Solution 4:

The solution works for me is like this:

String str = obj.getString("eventdate").replaceAll("\\D+", "");
String upToNCharacters = str.substring(0, Math.min(str.length(), 13));
DateFormat timeZoneFormat = newSimpleDateFormat("dd-MM-yyyy HH:mm:ss");
timeZoneFormat.setTimeZone(TimeZone.getTimeZone("GMT-8"));

Date time = new java.util.Date(Long.parseLong(upToNCharacters));
//                                System.out.println(time);
model.setDate(String.valueOf(timeZoneFormat.format(time)));

Use time variable where you want

Post a Comment for "How To Convert Timestamp Into Date Format In Java"