Timestamp in JavaScript

Posted by bynary on Fri, 18 Feb 2022 19:09:38 +0100

1, Convert to JavaScript timestamp

1.Date.now()
Use date Now() can get the current timestamp

Date.now();     //1645099205343
new Date().getTime()	1645099205343

2.Date.parse() converts a string or time object directly to a timestamp
However, this method is not recommended. The value at the millisecond level is converted to 000

Date.parse()     //1645099205000

3.valueOf()
Return the original value of the specified object through the valueOf() function to obtain the accurate timestamp value:

(new Date()).valueOf()			//1645099205343

4.getTime() directly obtains the millisecond value of time through the prototype method

new Date().getTime()		//1645099205343

5.Number()
Converts a time object to a number of type, that is, a timestamp

Number(new Date())     //1645099205343

2, js timestamp to time

You can use the new date format to convert the current time, for example:

new Date(1645099205343)      
 // Thu Feb 17 2022 20:00:05 GMT+0800 (CST)

⚠️: The timestamp parameter must be of type Number. If it is a string, the parsing result is invalid Date

If the time stamp is returned to the front end between the back ends, there are two conversion methods:

1. Generate 'yyyy/MM/dd up (down) noon hh:mm:ss' format

function getLocalTime(n){
	return new Date(parseInt(n)).toLocaleString().replace(/:\d{1,2}$/,'');
}
getLocalTime(1645099205343) //"8:00 pm on February 17, 2022"

It can also be used as follows. You can choose as many as you want. Note that spaces also count

function getLocalTime(n) {   
    return new Date(parseInt(n)).toLocaleString().substr(0,14)
}   
getLocalTime(1645099205343) //'2022 / 1 / 19 PM 5:'

Or use regular:

function getLocalTime(n){
	return new Date(parseInt(n)).toLocaleString().replace(/year|month/g,"-").replace(/day/g,"");
}
getLocalTime(1645099205343);    //"8:00:05 pm on February 17, 2022"

2. Generate 'yyyy MM DD HH: mm: Ss' format

First convert it into a data object, and then realize it by splicing regularization and other means:

function getData(n){
  n=new Date(n)
  return n.toLocaleDateString().replace(/\//g, "-") + " " + n.toTimeString().substr(0, 8)
}
getData(1645099205343) //'2022-2-17 20:00:05'

However, such a conversion will not work well in some browsers, because the toLocaleDateString() method varies from browser to browser.

It can be spliced by obtaining the month, year and day of the time respectively, so that the compatibility is better:

function getData(n) {
  let now = new Date(n),
    y = now.getFullYear(),
    m = now.getMonth() + 1,
    d = now.getDate();
  return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}
getData(1645099205343) //'2022-2-17 20:00:05'

3, Knowledge

1. Current system locale format (toLocaleDateString and toLocaleTimeString)

(new Date()).toLocaleDateString() + " " + (new Date()).toLocaleTimeString() 
//'2022 / 2 / 18 6:51:09 PM'

2. Ordinary string (toDateString and toTimeString)

(new Date()).toDateString() + " " + (new Date()).toTimeString() 
//"Fri Feb 18 2022 18:52:01 GMT+0800 (CST)" 

3. Greenwich mean time (toGMTString)

(new Date()).toGMTString() 
//"Fri, 18 Feb 2022 10:53:01 GMT"

4.Date object string (toString)

(new Date()).toString() 
//"Fri Feb 18 2022 18:59:35 GMT+0800 (CST)" 

4, Date object constructor

The Date object has several constructors:

new Date() 
new Date(milliseconds) 
new Date(datestring) 
new Date(year, month) 
new Date(year, month, day) 
new Date(year, month, day, hours) 
new Date(year, month, day, hours, minutes) 
new Date(year, month, day, hours, minutes, seconds) 
new Date(year, month, day, hours, minutes, seconds, microseconds) 

Description of Date object constructor parameters:

milliseconds - distance JavaScript Internally defined number of milliseconds from January 1, 1970 
datestring - The string represents the date and time of the. This string can be used Date.parse()transformation 
year - Four digit year, if the value is 0-99,Then add 1900 to it 
month - 0(Represents January)-11(On behalf of December)Months between 
day - 1-31 Date between 
hours - 0(Represents midnight)-23 Hours between 
minutes - 0-59 Minutes between 
seconds - 0-59 Seconds between 
microseconds - 0-999 Milliseconds between 

Date object return value

If there are no parameters, the current date will be returned;
If the parameter is a number, the number is treated as a millisecond value and converted to a date
If the parameter is a string, the string is regarded as the string representation of the date and converted to the date
You can also use six constructors to precisely define and return the time

let d1 = new Date(); 
document.write(d1.toString());  
//Fri Feb 18 2022 19:05:40 GMT+0800 (CST)
let d2 = new Date("2022-1-19 17:42:33"); 
document.write(d2.toString());  
//Fri Feb 18 2022 19:05:40 GMT+0800 (CST)Invalid Date
let d3 = new Date(2022, 1, 19); 
document.write(d3.toString());
//Fri Feb 18 2022 19:05:40 GMT+0800 (CST)Invalid DateSat Feb 19 2022 00:00:00 GMT+0800 (CST)

As a built-in object of JavaScript, Date must be created in the way of new.

The internal representation of Date object in JavaScript is the number of milliseconds (timestamp) from midnight (GMT) on January 1, 1970. Here, we also call the internal representation of Date as timestamp.

You can use getTime() to convert the Date object into the timestamp of Date, and setTime() can convert the timestamp of Date into the standard form of Date.

The Date function uses syntax

date. Method name (parameter 1, parameter 2,...); Date. Method name ();
Date represents an instance of a date object, and date represents a date object,
date. The method name is called as the member function of the object
Date. The method name is the static function called by the object

The Date function is classified by function

Date acquisition class function

Date() function – constructor of date object
getDate() function – returns the number of days (1-31) in the month in the date object
getDay() function – returns the number of days in the week (0-6) in the date object
getFullYear() function -- returns the four digit year in the date object
getHours() function – returns the number of hours (0-23) in the date object
getMilliseconds() function – returns the number of milliseconds (0-999) in the date object
getMinutes() function -- returns the number of minutes in the date object (0-59)
getMonth() function – returns the number of months (0-11) in the date object
getSeconds() function – returns the number of seconds (0-59) in the date object
getTime() function -- returns the timestamp representation (in milliseconds) of the date object
getTimezoneOffset() function -- returns the time difference between the local time and the current date in UTC, in minutes
getUTCDate() function -- returns the day (1-31) in the month represented by universal standard time (UTC) in the date object
getUTCDay() function -- returns the day of the week (0-6) expressed in UTC in the date object
getUTCFullYear() function -- returns the four digit year represented by world standard time (UTC) in the date object
Getuthours() function -- returns the number of hours (0-23) expressed in UTC in the date object
getUTCMilliseconds() function - returns the number of milliseconds (0-999) expressed in universal standard time (UTC) in the date object
getUTCMinutes() function -- returns the number of minutes (0-59) expressed in UTC in the date object
getUTCMonth() function -- returns the number of months (0-11) expressed in UTC in the date object
getUTCSeconds() function -- returns the number of seconds (0-59) expressed in UTC in the date object
getYear() function -- returns the year of the date object (real year minus 1900)
Date.UTC() function -- returns the number of milliseconds (timestamp) from the date object to midnight on January 1, 1970, UTC

Date setting class function

setDate() function – sets the day of the month in the date object and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setFullYear() function – sets the year, month, and day in the date object and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setHours() function – sets the hour, minute, second, and millisecond of the date object and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setMilliseconds() function – sets the number of milliseconds of the date object and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setMinutes() function – sets the minutes, seconds, and milliseconds of the date object, and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setMonth() function – sets the month and day in the date object, and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setSeconds() function – sets the day of the month in the date object and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setTime() function – sets the date object in milliseconds and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setUTCDate() function –
Sets the day of the month represented by universal standard time (UTC) in the date object, and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setUTCFullYear() function –
Sets the year, month, and day in the date object in UTC, and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setUTCHours() function -
Sets the hours, minutes, seconds, and milliseconds expressed in UTC in the date object, and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setUTCMilliseconds() function –
Sets the number of milliseconds expressed in UTC in the date object, and returns the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setUTCMinutes() function –
Set the minutes and seconds expressed in UTC in the date object, and return the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setUTCMonth() function –
Set the month and day expressed in UTC in the date object, and return the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setUTCSeconds() function –
Set the seconds and milliseconds expressed in UTC in the date object, and return the number of milliseconds (timestamp) between the date object and midnight on January 1, 1970
setYear() function – sets the year of the date object (real year minus 1900)

Date printing function

toDateString() function – returns a string representation of the date part of the date object
toGMTString() function -- returns the string representation of Greenwich mean time (GMT) of the date object
toLocaleDateString function – returns the localized string of the date part of the date object
toLocaleTimeString function – returns a localized string of the time portion of the date object
toTimeString() function – returns a string of the time part of the date object
toUTCString function -- returns a string representation of the world standard time (UTC) of the date object

5, JavaScript timestamp and php timestamp conversion

js timestamp is usually 13 bits, while php timestamp is 10 bits. The conversion function is as follows:

let nowtime = (new Date).getTime();/*Current timestamp*/   
/*Conversion time, calculate the difference*/   
function comptime(beginTime,endTime){   
    var secondNum = parseInt((endTime-beginTime*1000)/1000);//Calculate timestamp difference      
    if(secondNum>=0&&secondNum<60){   
        return secondNum+'Seconds ago';   
    }   
    else if (secondNum>=60&&secondNum<3600){   
        var nTime=parseInt(secondNum/60);   
        return nTime+'Minutes ago';   
    }   
    else if (secondNum>=3600&&secondNum<3600*24){   
        var nTime=parseInt(secondNum/3600);   
        return nTime+'Hours ago';   
    }   
    else{   
        var nTime = parseInt(secondNum/86400);   
        return nTime+'Days ago';   
    }   
} 
t = comptime("1642471746",nowtime); //1642471746 is the timestamp returned by PHP through ajax, which is 10 bits
console.log(t); //27 minutes ago

Topics: Javascript Front-end