Many application scenarios need to be converted between the UNIX timestamp and the Datetime object. Unix timestamp represents the number of seconds since the UNIX Era (January 1, 1970 00:00:00 UTC), and the DateTime object represents time in a more intuitive way, including specific date and time component.
converted from UNIX timestamp to Datetime object
Convert the UNIX timestamp to the Datetime object, you can use the following methods:
For Java developers, because the timestamp is in milliseconds, the conversion method is different:
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp) { // Unix 时间戳是自纪元以来的秒数 DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.AddSeconds(unixTimeStamp).ToLocalTime(); return dateTime; }
public static DateTime JavaTimeStampToDateTime(long javaTimeStamp) { // Java 时间戳是自纪元以来的毫秒数 DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dateTime = dateTime.plusMillis((long) javaTimeStamp).toLocalTime(); return dateTime; }
Inverse conversion can use the following code fragment:
For Java, the method of converting the Datetime object into a Java timestamp (millisecond) is as follows:
public double DateTimeToUnixTimeStamp(DateTime dateTime) { // Unix 时间戳是自纪元以来的秒数 DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan span = (dateTime - epoch).ToLocalTime(); return span.TotalSeconds; }
The above is the detailed content of How to Convert Between Unix Timestamps and DateTime Objects?. For more information, please follow other related articles on the PHP Chinese website!