Believe that many people at work will encounter the need to convert timestamp (timestamp) to a DateTime type, especially when doing web site development, sometimes need to transfer the front end of the timestamp to a datetime type, and in the process of turning to find the need to pay attention to.
First of all, the way to generate timestamp in JavaScript is generally the following:
Var date = new date ();
/ / get the timestamp
Var timestamp1 = date. GetTime ();
Var timestamp2 = Date. Now ();
Var timestamp3 = date. The valueOf ();
// output the current time
The console. The info (" date. ToString: "and the date. The toString ());
The console. The info (" date. ToLocaleString: "and the date. ToLocaleString ());
// output timestamp
The console. The info (" date. GetTime: "timestamp1);
The console. The info (" date. Now: "timestamp2);
The console. The info (" date. The valueOf: "timestamp3);
My current result shows:
Then in c# you need to convert the timestamp to timestamp (as for how the front end transfers data to the back end, it's not within the scope of this chapter) :
String timestampStr = "1481038051980";
Long timestamp = long. Parse (timestampStr);
DateTime dt = new DateTime(1971,1,1,0,0).AddMilliseconds(timestamp);
Console. WriteLine (dt);
The Console. ReadKey ();
However, something amazing happened and the results were as follows:
No, the time stamp generated by js above is 11:27:31 PM on December 6, 2016 (Tue Dec 06, 2016 23:27:31), which means the date display is correct, but the time is wrong, I have been struggling with it, and I even suspect that I have forgotten the generation method of js time stamp, so I check the document, yes, what's the matter with that? Finally, it occurred to me that it might have something to do with time zone, so I added a line of code:
String timestampStr = "1481038051980";
Long timestamp = long. Parse (timestampStr);
DateTime dt = new DateTime(1971,1,1,0,0).AddMilliseconds(timestamp);
Console. WriteLine (dt);
Console. WriteLine (dt) ToLocalTime ());
Yes, just call the ToLocalTime() method, and the result is as follows:
It's that simple. It's just a matter of time zone
Convert the javascript timestamp to the c# datetime type