Search code examples
javarandomdatetime-formatepochmilliseconds

Can I get value of Curren time from miliseconds value


I have a value in miliseconds 1601626934449

Which generated via https://docs.oracle.com/javase/7/docs/api/java/lang/System.html#currentTimeMillis()

but can I somehow be able to get time in human readable format, or in brief I need to be able to know what the value in miliseconds 1601626934449 is ?


Solution

  • Use java.time on Java 8 or higher. Using that, it's easy to reach your goal.
    You basically create an Instant from the epoch milliseconds (which represent a moment in time), make it a ZonedDateTime by applying a ZoneId (my system's default in the following example) and then either format the output String by a built-in DateTimeFormatter or by creating a custom one with a desired pattern to make it as human-readable as required.

    Here's an example:

    public static void main(String[] args) {
        // your example millis
        long currentMillis = 1601626934449L;
        // create an instant from those millis
        Instant instant = Instant.ofEpochMilli(currentMillis);
        // use that instant and a time zone in order to get a suitable datetime object
        ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
        // then print the (implicitly called) toString() method of it
        System.out.println(currentMillis + " is " + zdt);
        // or create a different human-readable formatting by means of a custom formatter
        System.out.println(
            zdt.format(
                DateTimeFormatter.ofPattern(
                    "EEEE, dd. 'of' MMMM uuuu 'at' HH:mm:ss 'o''clock in' VV 'with an offset of' xxx 'hours'",
                    Locale.ENGLISH
                )
            )
        );
    }
    

    which outputs (on my system)

    1601626934449 is 2020-10-02T10:22:14.449+02:00[Europe/Berlin]
    Friday, 02. of October 2020 at 10:22:14 o'clock in Europe/Berlin with an offset of +02:00 hours