📅  最后修改于: 2023-12-03 14:39:42.799000             🧑  作者: Mango
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.
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.
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 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.
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.
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
.
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.