-1

(Using Java 11) How can I convert the following epoch long value:

long epochLong = 1496760826841L

into this string:

Jun 6, 2017 3:53:46 PM
rmf
  • 625
  • 2
  • 9
  • 39
  • 1
    [`DateTimeFormatter`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/time/format/DateTimeFormatter.html) – Petr Janeček Apr 06 '22 at 10:40
  • Please search before asking. Very similar questions have been answered more than once before. – Ole V.V. Apr 06 '22 at 12:00
  • Let Java localize for you. `Instant.ofEpochMilli(1_496_760_826_841L).atZone(ZoneId.of("Africa/Porto-Novo")).format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM).withLocale(Locale.US))` gives `Jun 6, 2017, 3:53:46 PM` (tested on Java 17). – Ole V.V. Apr 06 '22 at 12:15

1 Answers1

3

This should work if you want Jun 06, 2017 3:53:46 PM irrespective of the JVM machine time zone change the triggerTime to this

LocalDateTime triggerTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), ZoneId.of("+01:00"));

public static void main(String[] args) {
        long epochMillis = 1496760826841L;
        LocalDateTime triggerTime =
                LocalDateTime.ofInstant(Instant.ofEpochMilli(epochMillis),
                        TimeZone.getDefault().toZoneId());
        DateTimeFormatter parseFormatter
                = DateTimeFormatter.ofPattern("MMM dd, yyyy  h:m:s a");
        
        System.out.println(triggerTime.format(parseFormatter));
    }
HariHaravelan
  • 1,041
  • 1
  • 10
  • 19
  • 1
    Only don’t use `TimeZone`. That class is poorly designed and long outdated. To get the JVM’s default time zone, just use `ZoneId.systemDefault()`. A good answer, thanks. – Ole V.V. Apr 06 '22 at 11:49