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

How to Convert Between Unix Timestamps and DateTime Objects?

DDD
Release: 2025-02-01 23:46:10
Original
302 people have browsed it

How to Convert Between Unix Timestamps and DateTime Objects?

UNIX timestamp and Datetime object conversion detailed explanation

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:

<code class="language-csharp">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

converted from the DateTime object to Unix timestamp

<code class="language-java">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;
}</code>
Copy after login

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:

<code class="language-csharp">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;
}</code>
Copy after login
These methods provide a conversion method between high -efficiency and reliable Unix timestamps and DateTime objects to meet different needs in various application scenarios in various application scenarios.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template