Home > Backend Development > C++ > How to Convert Between Unix Timestamps and DateTime Objects in .NET and Java?

How to Convert Between Unix Timestamps and DateTime Objects in .NET and Java?

Linda Hamilton
Release: 2025-02-01 23:41:10
Original
484 people have browsed it

How to Convert Between Unix Timestamps and DateTime Objects in .NET and Java?

<.> 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>
Copy after login

Convert datetime to unix timestamp

<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>
Copy after login

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>
Copy after login
. The .NET example remains unchanged because the code fragment itself has used the Datetime class of the .NET.
<code class="language-java">// Java代码示例
public static long DateTimeToJavaTimeStamp(java.time.LocalDateTime dateTime) {
    return dateTime.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli();
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template