内容目录
Using JSON to store time requires converting it to an object in the following format:
2019-12-06T17:15:52Z
The 'Z' indicates the time zone.
For example, to represent Beijing time:
2019-12-06T17:15:52+08:00
However, coordinating time conversions between the front-end, C#, and database time handling can be quite cumbersome, and converting JSON and string to time also adds complexity.
Based on the author’s verification, it is recommended to pass the time in UNIX timestamp form.
The C# code to quickly convert the current time to a timestamp (in seconds) is as follows:
(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000 / 1000
If you want it in milliseconds:
(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000
Common C# time conversion code:
/// <summary>
/// Get the number of seconds from 1970-01-01 to dateTime, without a time zone
/// </summary>
public static long GetTimestamp(DateTime dateTime)
{
DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
return (dateTime.Ticks - dt1970.Ticks) / 10000 / 1000;
}
/// <summary>
/// Calculate the date from the timestamp (in seconds), without a time zone
/// </summary>
public static DateTime NewDate(long timestamp)
{
DateTime dt1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0);
long t = dt1970.Ticks + timestamp * 10000 * 1000;
return new DateTime(t);
}
/// <summary>
/// Convert a string to time
/// </summary>
/// <param name="dateString"></param>
/// <returns></returns>
public static DateTime StringToDateTime(string dateString)
{
// The format must be 2019-03-13 14:49:10.8327809
DateTime dt = Convert.ToDateTime(dateString, System.Globalization.CultureInfo.CurrentCulture);
return dt;
}
文章评论