This article mainly introduces the C # datetime and timestamp conversion instance, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.
C # datetime-to-timestamp conversions, including JavaScript timestamps and Unix timestamps.
1. What is a timestamp
The first thing to know is the difference between JavaScript and UNIX timestamps:
JavaScript Timestamp: GMT January 01, 1970 00:00 00 seconds (Beijing time January 01, 1970 08:00 00 seconds) up to now the total number of milliseconds.
Unix Timestamp: GMT January 01, 1970 00:00 00 seconds (Beijing time January 01, 1970 08:00 00 seconds) up to now the total number of seconds.
You can see the total number of milliseconds for the JavaScript timestamp, and the Unix timestamp is the total number of seconds.
Like the same thing. 2016/11/03 12:30:00, converted to a JavaScript timestamp of 1478147400000, and converted to a Unix timestamp of 1478147400.
2. JavaScript timestamps convert each other
2.1 C # DateTime conversion 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 milliseconds
System.Console.WriteLine (timeStamp);
2.2 JavaScript timestamp conversion 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 timestamps convert each other
3.1 C # datetime conversion 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; // seconds difference
System.Console.WriteLine (timeStamp);
3.2 Unix timestamp conversion 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"));