-4

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?

7
  • 2
    why is not working? what is the exception? Commented Dec 3, 2016 at 8:31
  • 2
    Is time your string? If so, it's not clear how you'd expect that to work... but "It not works" is never enough information to include in a question. Please read codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question Commented Dec 3, 2016 at 8:42
  • Welcome to Stack Overflow! Please review our SO Question Checklist to help you to ask a good question, and thus get a good answer. Commented Dec 3, 2016 at 8:48
  • You cannot do DateFormat.format("dd-MM-yyyy", cal). It would require that DateFormat had a static method format that accepted two arguments. The format method is not static, so you need to create a DateFormat object and call the method on that object. The method exists in overloaded versions taking 1 and 3 arguments, respectively, not 2. Commented Dec 3, 2016 at 10:46
  • I will remember ur suggestions Sir @ Jon Skeet,@ Joe C Commented Dec 3, 2016 at 10:52

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

Great! This (improving a two-year-old answer) is inspiring!
1

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

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

Comments

1

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

1 Comment

My guess is the dash between the digits is a sign and part of the time zone. If so, the zone offset is not 0800 as your guess said, but -0800.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.