0

I am trying to convert Unix epoch time to an ISO 8601 (https://en.wikipedia.org/wiki/ISO_8601) with the time zone. I have it working but only if it's local time. How can I pass in the time zone as an offset?

Input 1: 1483772400000

Input 2: -0700 (but I can convert as needed)

Desired output: 2017-01-07T00:00:00-07:00 or simply 2017-01-07T00:00:00-07

Current output: 2017-01-06 23:00:00-08 as I'm in PST

I'm using IntelliJ IDEA, JDK 1.8u202 .

    package util.date;
    
    import java.util.Date;
    import java.util.Locale;
    import java.util.TimeZone;
    import java.text.SimpleDateFormat;
    
    public class EpochToISO {
        public String epochToIso8601(long time) {
            String format = "yyyy-MM-dd HH:mm:ssX";
            SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.getDefault());
            sdf.setTimeZone(TimeZone.getDefault());
            return sdf.format(new Date(time));
        }
    
        public static void main(String[] args) {
            EpochToISO convert = new EpochToISO();
            long epoch = 1483772400000; // Example
            String iso8601 = convert.epochToIso8601(epoch);
            System.out.println(epoch + " -> " + iso8601);
        }
    }
Vy Do
  • 46,709
  • 59
  • 215
  • 313
Ryan B
  • 37
  • 5
  • Please consider adding the `time` tag. It may attract users better suited to your problem and better describes your problem. – Michael M. Sep 14 '22 at 01:41
  • Does this answer your question? [ISO8601 format in java given seconds](https://stackoverflow.com/questions/48039785/iso8601-format-in-java-given-seconds) – Steffen Sep 14 '22 at 01:45

1 Answers1

0

TimeZone.getDefault() is used to get the TimeZone of host machine on which code is executed on. You can provide the TimeZone for which you want to obtain the datetime. Ex:

TimeZone timeZone = TimeZone.getTimeZone("America/Creston"); 
sdf.setTimeZone(timeZone);

TimeZones with GMT/UTC Offsets https://code2care.org/pages/java-timezone-list-utc-gmt-offset

b.s
  • 2,409
  • 2
  • 16
  • 26