简体   繁体   中英

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 cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time);
    String date = DateFormat.format("dd-MM-yyyy", cal).toString();
    return date;
}

How to convert this Timestamp into Date format?

Parse directly into an OffsetDateTime

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

private static final DateTimeFormatter JSON_TIMESTAMP_FORMATTER 
        = new DateTimeFormatterBuilder()
                .appendLiteral("/Date(")
                .appendValue(ChronoField.INSTANT_SECONDS, 1, 19, SignStyle.NEVER)
                .appendValue(ChronoField.MILLI_OF_SECOND, 3)
                .appendOffset("+HHMM", "Z")
                .appendLiteral(")/")
                .toFormatter();

Then just do:

    String time = "/Date(1479974400000-0800)/";
    OffsetDateTime odt = OffsetDateTime.parse(time, JSON_TIMESTAMP_FORMATTER);
    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. This is also why I specify in the formatter that the seconds must not be signed.

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: parse the milliseconds and the offset separately and combine

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:

    String time = "/Date(1479974400000-0800)/";
    Pattern pat = Pattern.compile("/Date\\((\\d+)([+-]\\d{4})\\)/");
    Matcher m = pat.matcher(time);
    if (m.matches()) {
        Instant i = 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

Thu Nov 24 09:00:00 CET 2016

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

如果按日期表示 Date 实例,那么您可以这样做:

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

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"));
Date time = new java.util.Date(Long.parseLong(allTimeInfo[0]));
System.out.println(time);
System.out.println(timeZoneFormat.format(time));

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 = new SimpleDateFormat("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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM