Convert epoch millisecond timestamp to readable datetime
In many cases such as when dealing with API response in JSON format, working on JavaScript assets embedded on websites, and so on, we keep seeing 13-digit long numbers very frequently and we probably know it is epoch timestamp originating from code like new Date().getTime()
, however, as a human we just can not quickly tell what date and time it represents. There is a convenient website named Epoch Converter that can help convert it to human-readable format easily but most of the time for developers, there are even quicker ways than opening the website, which is by using the interactive shell
that comes with many programming languages.
In Node.js/JavaScript
// node or browser console
> new Date(1685506340672)
2023-05-31T04:12:20.672Z
In Java
// jshell jdk 9+
import java.time.*;
jshell> Instant.ofEpochMilli(1685506340672L).atZone(ZoneId.of("Asia/Tokyo"))
//$1 ==> 2023-05-31T13:12:20.672+09:00[Asia/Tokyo]
In Ruby
# irb
irb(main):001:0> Time.at(0, 1685506340672, :millisecond)
=> 2023-05-31 13:12:20.672 +0900
In Python
>>> from datetime import datetime
>>> d = datetime.fromtimestamp(1685506340672/1000)
>>> str(d)
'2023-05-31 13:12:20.672000'