Search code examples
javadateutc

Java exact Date to String conversion (no local GMT offset)


I'm trying to do a very simple task. Convert a time (long myTime) in epoch seconds, to a String (but without any adjustment).

DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Instant AA = Instant.ofEpochSecond(myTime);
String reportDate = df.format(Date.from(AA));

The "reportDate" is automatically adjusted with GMT offset of Windows. I need instead the exact instant to string conversion. I'm new on Java ....


Solution

  • Set the time zone specifically

    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    

    This sets the offset to whatever you need so it will output the same date time on any server.