js convert Date date object to timestamp

Convert Date object to timestamp

The first method , using the Number() method, is accurate to milliseconds

[javascript]  view plain copy  
  1. var newDay = new Date();  
  2. console.log(Number(newDay));  
Returns the timestamp of the current time

The second method is to use the Date.parse() method of the date object, accurate to seconds

[javascript]  view plain copy  
  1. var newDay = new Date();  
  2. console.log(Date.parse(newDay));  

also returns the timestamp of the current time

The third method is to use the escape character to escape

[javascript]  view plain copy  
  1. var newDay = +new Date();  
  2.                 console.log(newDay);  


The fourth method is getTime(), which is accurate to milliseconds

var str = '2013-08-30'; // Date string 

str = str.replace(/-/g,'/'); // Replace - with /, because the following constructor only supports / delimited Date string

var date = new Date(str); // Construct a date data, the value is the incoming string
In the above, new Date(str) constructs a date. The parameter str must provide at least three parts of year, month and day, that is, a string in the form of "2013/03/08", not "2013/03", otherwise it will get a NaN. The time constructed at this time is: 2013/03/08 00:00:00. At the same time, you can also pass in hours, minutes and seconds, but not only hours, such as "2013/03/08 17", such parameters will also get a NaN. The parameter can be "2013/03/08 17:20" or "2013/03/08 17:20:05", which can get the correct time. If the seconds are not given, the default is 0. 

At this time, the date data is obtained. If you want to get the so-called timestamp above, you can do this:
var time = date.getTime();

This is a numerical value that represents the number of milliseconds from 0:00:00 on January 1, 1970 to the moment of the date . If you divide this number by 1000, you will get the number of seconds, and continue to divide by 60. , to get minutes, divide by 60 to get hours, etc.

The fifth method is (new Date).valueOf(), which is accurate to milliseconds

Comparing the two methods,

The timestamp returned by the first method using a number object is accurate to milliseconds, while the Date.parse() method of a date object is only accurate to seconds, and the last three digits are filled with 0, so I personally recommend the first one


Convert timestamp to Date object

[javascript]  view plain copy  
  1. var  newDate =  new  Date(timestamp);   //Instantiate a Date object and pass in the timestamp directly, note that it must be 13 digits  
or
[javascript]  view plain copy  
  1. var  timestamp3 = 1403058804000;   //declare a timestamp  
  2. var  newDate =  new  Date();   //Instantiate a Date object  
  3. newDate.setTime(timestamp3);  //Set the time of the Date object to the time of the timestamp  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325902504&siteId=291194637