<.> In the .NET and Java to convert unix timestamps and datetime objects
In .NET or Java, it is often necessary to convert between the UNIX timestamp (the number of seconds or milliseconds since the Era) and the DateTime object.
Convert the UNIX timestamp to datetime
In .NET, use the following code to convert UNIX timestamp (in seconds) to dates:
In Java, the timestamp is in milliseconds, and this code is used:
<code class="language-C#">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; }</code>
<code class="language-java">// Java代码示例,此处应使用Java的日期时间类,而非.NET的DateTime public static java.time.LocalDateTime JavaTimeStampToDateTime(long javaTimeStamp) { return java.time.Instant.ofEpochMilli(javaTimeStamp).atZone(java.time.ZoneId.systemDefault()).toLocalDateTime(); }</code>
To convert DateTime into UNIX timestamps, just reverse the process:
Please note that the Java example uses the class in the
package provided by the Java 8 and above versions, which provides a more modern and robust date and time processing method than the old<code class="language-C#">public double DateTimeToUnixTimeStamp(DateTime dateTime) { DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); TimeSpan span = dateTime.ToUniversalTime() - epoch; return span.TotalSeconds; }</code>
<code class="language-java">// Java代码示例 public static long DateTimeToJavaTimeStamp(java.time.LocalDateTime dateTime) { return dateTime.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli(); }</code>
The above is the detailed content of How to Convert Between Unix Timestamps and DateTime Objects in .NET and Java?. For more information, please follow other related articles on the PHP Chinese website!