Home  >  Article  >  Web Front-end  >  How to set time format in javascript

How to set time format in javascript

PHPz
PHPzOriginal
2023-04-26 14:30:352039browse

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.

  1. toDateString() method

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
  1. toTimeString() method

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 (中国标准时间)
  1. toLocaleDateString() method

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
  1. toLocaleTimeString() method

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
  1. toISOString() method

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
  1. Custom format

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn