Home > Software design >  How to convert timestamp from GMT to Unix epoch
How to convert timestamp from GMT to Unix epoch

Time:07-07

I'm parsing a timestamp which is "2022-01-12T17:17:34.512492 0000", this format is "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'ZZZZ" (ISO8601).

I want to convert it in epoch unix time, I'm using java.text.SimpleDateFormat. I tried two methods but both don't work:

1- First Method

val parsed = "2022-01-12T17:17:34.512492 0000"
val df: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'ZZZZ'")
val date = df.parse(parsed.toString)
val epoch = date.getTime

Error showed:

java.text.ParseException: Unparseable date: "2022-01-12T17:17:34.512492 0000"

2- This second Method shows an output but is incorrect

val parsed = "2022-01-12T17:17:34.512492 0000"
val df: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS' 0000'")
val date = df.parse(parsed.toString)
val epoch = date.getTime
println(epoch)

Output:

1642004766492

If you convert this epoch to HUMAN DATE: "Wednesday, 12 January 2022 16:26:06.492"

The hours,minutes and seconds are wrong.

CodePudding user response:

looks like epoch has data in internal datetime format. and you should convert it to string format like this in java

    public static String dateToString(Date d, String string_format) {
        String result = "";
        if(d != null) {
            result = new SimpleDateFormat(string_format).format(d);
        }
        return result;
    }

CodePudding user response:

The timestamp you have has microseconds precision. Such precision is not supported by SimpleDateFormat. Also, Unix epoch time is usually up to milliseconds precision.

Possible solution here is to explicitly round the microseconds to milliseconds in the string before parsing, then use the yyyy-MM-dd'T'HH:mm:ss.SSSZ format.

String parsed = "2022-01-12T17:17:34.512492 0000";

String upToSeconds = parsed.substring(0, "yyyy-MM-ddTHH:mm:ss".length());
String microseconds = parsed.substring("yyyy-MM-ddTHH:mm:ss.".length(), "yyyy-MM-ddTHH:mm:ss.".length()   "SSSSSS".length());
String timezone = parsed.substring("yyyy-MM-ddTHH:mm:ss.SSSSSS".length());

String roundedMilliseconds = new BigDecimal(microseconds).divide(new BigDecimal("1000"), 0, RoundingMode.HALF_UP).toString();

String reformatted = upToSeconds   "."   roundedMilliseconds   timezone;
System.out.println(reformatted); // 2022-01-12T17:17:34.512 0000

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
long epoch = sdf.parse(reformatted).getTime();

System.out.println(epoch); // 1642007854512
System.out.println(Instant.ofEpochMilli(epoch)); // 2022-01-12T17:17:34.512Z
  • Related