📅  最后修改于: 2023-12-03 14:39:44.327000             🧑  作者: Mango
As a .NET developer, you may need to work with timestamps frequently. The DateTime
struct in C# provides a way to handle dates and times, representing them as a number of ticks that have elapsed since 12:00 midnight, January 1, 0001.
To get the current timestamp in C#, you can use the DateTime.UtcNow
property, which returns the current UTC date and time. You can then convert it to a Unix timestamp (number of seconds that have elapsed since January 1, 1970) using the DateTimeOffset.ToUnixTimeSeconds
method:
DateTimeOffset now = DateTimeOffset.UtcNow;
long timestamp = now.ToUnixTimeSeconds();
Alternatively, you can use the DateTimeOffset.ToUnixTimeMilliseconds
method to get the timestamp in milliseconds:
DateTimeOffset now = DateTimeOffset.UtcNow;
long timestamp = now.ToUnixTimeMilliseconds();
Note that DateTime.UtcNow
returns the current date and time in UTC time zone, which is independent of the local time zone. If you need to get the current date and time in the local time zone, you can use DateTime.Now
instead:
DateTimeOffset now = DateTimeOffset.Now;
long timestamp = now.ToUnixTimeSeconds();
To convert a Unix timestamp back to a DateTime
object, you can create a new DateTimeOffset
object from the timestamp and then use the DateTimeOffset.LocalDateTime
property to get the local date and time:
long timestamp = 1627561667;
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(timestamp);
DateTime localDateTime = dateTimeOffset.LocalDateTime;
Similarly, you can use the DateTimeOffset.FromUnixTimeMilliseconds
method to convert a timestamp in milliseconds:
long timestamp = 1627561667000;
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
DateTime localDateTime = dateTimeOffset.LocalDateTime;
In this tutorial, you learned how to get the current timestamp and convert it to a DateTime
object in C#. With this knowledge, you can handle dates and times more efficiently in your .NET applications.