C DateTime and timestamp conversion instance
- 2021-12-13 16:47:45
- OfStack
The conversion between C # DateTime and timestamp, including JavaScript timestamp and Unix timestamp.
1. What is a timestamp
First of all, we should know the difference between the timestamps of JavaScript and Unix:
JavaScript timestamp: It refers to the total milliseconds from 00:00: 00 GMT on January 1, 1970 (08: 00: 00 Beijing time on January 1, 1970) to the present.
Unix timestamp: It refers to the total number of seconds from 00:00: 00 GMT on January 1, 1970 (08: 00: 00 Beijing time on January 1, 1970) to the present.
You can see the total number of milliseconds of JavaScript timestamp and the total number of seconds of Unix timestamp.
For example, the same 2016/11/03 12:30, converted to JavaScript timestamp is 1478147400000; Convert to Unix timestamp 1478147400.
2. JavaScript timestamp conversion to each other
2.1 C # DateTime to JavaScript timestamp
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // Local time zone
long timeStamp = (long)(DateTime.Now - startTime).TotalMilliseconds; // Difference in milliseconds
System.Console.WriteLine(timeStamp);
2.2 JavaScript timestamp is converted to C # DateTime
long jsTimeStamp = 1478169023479;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // Local time zone
DateTime dt = startTime.AddMilliseconds(jsTimeStamp);
System.Console.WriteLine(dt.ToString("yyyy/MM/dd HH:mm:ss:ffff"));
3. Unix timestamp conversion to each other
3.1 C # DateTime to Unix timestamp
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // Local time zone
long timeStamp = (long)(DateTime.Now - startTime).TotalSeconds; // Difference in seconds
System.Console.WriteLine(timeStamp);
3.2 Unix timestamp is converted to C # DateTime
long unixTimeStamp = 1478162177;
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // Local time zone
DateTime dt = startTime.AddSeconds(unixTimeStamp);
System.Console.WriteLine(dt.ToString("yyyy/MM/dd HH:mm:ss:ffff"));