slinden77 slinden77 - 3 months ago 37
Java Question

Changing unix timestamp to ISO8601 timestamp

I need to convert a unix timestamp (millis) to ISO8601.
A solution with JodaTime is fine, I can't figure it out.

EDIT: I am using this as per the accepted solution:

public static String getISO8601StringFromMillis(long millis){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.format(new Date(millis));
}

Answer

Try following.

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TestDate {
    public static void main(String[] args) {
        System.out.println(getDate(1471377707203L));
    }

    public static String getDate(long timestamp) {
        TimeZone timezone = TimeZone.getTimeZone("UTC");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
        dateFormat.setTimeZone(timezone);
        String isoStr = dateFormat.format(new Date(timestamp));


        return isoStr;
    }
}
Comments