Home >Web Front-end >Front-end Q&A >How to set time format in javascript
In JavaScript, we can use Date objects to represent dates and times. When we need to display the time in a specific format, JavaScript provides us with some methods to set the time format.
This method returns a string representing the value of the date part. It is expressed as an abbreviated month plus a numeric day and a four-digit year.
let date = new Date(); console.log(date.toDateString()); //输出Tue May 25 2021
This method returns a string representing the value of the time part. It is expressed in hours, minutes, seconds and time zone.
let date = new Date(); console.log(date.toTimeString()); //输出14:29:35 GMT+0800 (中国标准时间)
This method returns a string that represents the value of the date part and is displayed according to the localized format. It is expressed in the order of localized numeric date, month, and year.
let date = new Date(); console.log(date.toLocaleDateString()); //输出2021/5/25
This method returns a string that represents the value of the time part and is displayed according to the localized format. It is expressed in the localized order of hours, minutes, and seconds.
let date = new Date(); console.log(date.toLocaleTimeString()); //输出下午2:29:35
This method returns an ISO format string, representing the complete date and time, and the time zone is UTC.
let date = new Date(); console.log(date.toISOString()); //输出2021-05-25T06:29:35.115Z
If the above method cannot meet our needs, we can use some JavaScript libraries to customize the time format. For example, time can be easily formatted using the Moment.js library. After installing the Moment.js library, we can use it as follows:
let date = new Date(); console.log(moment(date).format('YYYY年MM月DD日 hh:mm:ss')); //输出2021年05月25日 02:29:35
The above are some methods of setting time format in JavaScript, which can be freely chosen according to our needs.
The above is the detailed content of How to set time format in javascript. For more information, please follow other related articles on the PHP Chinese website!