Search code examples
javacassandradatetime-formattimezone-offsetmilliseconds

convert milliseconds to java date with offset hours (Z05:00)


How to convert string value in milliseconds to the string of date format as "2006-01-02T15:04:05Z07:00"? (inlcuding offset with Z)


Solution

  • Edit: Your string is a placeholder string

    I believe that "2006-01-02T15:04:05Z07:00" is Golang’s way to specify a date-time format. An ISO 8601 format to be more precise. The actual formatted string would be like for example 2018-09-19T00:26:42-05:00. So use DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXXX") or just DatetimeFormatter.ISO_OFFSET_DATE_TIME (and no substitutions after the formatter has formatted the string).

    Original answer

    This goes in two steps:

    1. Convert your milliseconds string (I assume since the epoch of 1970-01-01) to an Instant.
    2. Convert the Instant to the desired time zone and format it.

    The challenge is with the second step. Offsets have signs, positive or negative, and the standard formatting options for offsets include either - or + (except that offset zero is sometimes written as just Z without sign). Here’s my go at the whole thing:

        ZoneId zone = ZoneId.of("America/Denver");
        DateTimeFormatter firstShotFormatter
                = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss'Z'xxx");
    
        String milliseconds = "1136239445000";
    
        Instant pointInTime = Instant.ofEpochMilli(Long.parseLong(milliseconds));
        String firstShot = pointInTime.atZone(zone).format(firstShotFormatter);
        // Offset should be negative
        if (firstShot.contains("Z-")) {
            // Remove minus sign from formatted offset
            String result = firstShot.replace("Z-", "Z");
            System.out.println("Formatted string: " + result);
        } else {
            throw new IllegalStateException(
                    "Don’t know how to format a positive offset from UTC");
        }
    

    The output from this snippet is:

    Formatted string: 2006-01-02T15:04:05Z07:00

    I have tentatively guessed that your offset of Z07:00 referred to North American Mountain Time, which is at offset -07:00 in January. Please check. I didn’t know how to handle a positive offset, so my code checks that it doesn’t occur.

    I find the format you asked for peculiar. It ressembles ISO 8601 with its characteristic T between the date and the time part. But to the best of my knowledge ISO 8601 would have the offset as either Z (for zero) or signed, for example -07:00, never a mixture of those. You may want to check if you can persuade the receiver of your formatted string to accept a straight ISO 8601 string instead. I’d find this much cleaner and in the end easier to understand for all parties.

    Links