📜  c# datetime now timestamp - C# (1)

📅  最后修改于: 2023-12-03 14:39:42.799000             🧑  作者: Mango

C# DateTime Now Timestamp - C#

In C#, the DateTime struct provides various methods and properties to work with date and time. One of the common use cases is to retrieve the current date and time as a timestamp.

DateTime.Now

The DateTime.Now property returns a DateTime object that represents the current date and time according to the local machine's system clock.

DateTime now = DateTime.Now;

The now variable will hold the current date and time in the local time zone.

Timestamp Conversion

A timestamp represents a specific point in time as the number of milliseconds (or sometimes seconds) since a specific reference date and time (e.g., January 1, 1970). In C#, you can convert a DateTime object to a timestamp in various ways:

Unix Timestamp

Unix timestamp represents the number of seconds since January 1, 1970, at 00:00:00 UTC.

DateTime now = DateTime.Now;
long timeStamp = (long)(now - new DateTime(1970, 1, 1)).TotalSeconds;

The timeStamp variable will hold the Unix timestamp.

Millisecond Timestamp

If you need a timestamp with millisecond precision, you can use the DateTime.Ticks property.

DateTime now = DateTime.Now;
long timeStamp = now.Ticks / TimeSpan.TicksPerMillisecond;

The timeStamp variable will hold the millisecond timestamp.

DateTimeOffset

If you require handling time zones or working with dates and times in different time zones, you can use the DateTimeOffset struct. It represents a specific date and time together with an offset from UTC.

DateTimeOffset now = DateTimeOffset.Now;
long timeStamp = now.ToUnixTimeMilliseconds();

The timeStamp variable will hold the millisecond timestamp using DateTimeOffset.

Summary

In this tutorial, we explored how to retrieve the current date and time in C# using DateTime.Now. Additionally, we learned how to convert a DateTime object to timestamps such as Unix timestamp or millisecond timestamp. The DateTimeOffset struct is introduced as an alternative for handling time zones.

To summarize, DateTime.Now provides the current date and time, while various conversion methods and properties can be used to obtain timestamps representing specific points in time.