乐闻世界logo
搜索文章和话题

How do i format a date in javascript

4个答案

1
2
3
4

Formatting dates in JavaScript can typically be achieved through several methods:

1. Using Built-in Methods of the Date Object

The Date object in JavaScript provides several methods to retrieve different parts of the date and time (e.g., year, month, day, hour, minute, second), which you can then assemble into any desired format.

javascript
const date = new Date(); const year = date.getFullYear(); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const day = date.getDate().toString().padStart(2, '0'); const formattedDate = `${year}-${month}-${day}`; console.log(formattedDate); // Output format like: '2023-03-10'

2. Using Third-Party Libraries

Many developers choose to use third-party libraries like Moment.js or date-fns for handling dates and times. These libraries offer simple APIs for formatting dates.

Using Moment.js

javascript
const moment = require('moment'); const formattedDate = moment().format('YYYY-MM-DD'); console.log(formattedDate); // Output format like: '2023-03-10'

Using date-fns

javascript
const { format } = require('date-fns'); const formattedDate = format(new Date(), 'yyyy-MM-dd'); console.log(formattedDate); // Output format like: '2023-03-10'

3. Using the Internationalization API Intl.DateTimeFormat

ES6 introduced an internationalization API Intl, which includes a DateTimeFormat object for formatting dates.

javascript
const date = new Date(); const formatter = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', }); const formattedDate = formatter.format(date); console.log(formattedDate); // Output format like: '03/10/2023'

The above example demonstrates how to use Intl.DateTimeFormat to format dates in the American format (month/day/year). The advantage of this API is that it supports localization, allowing you to easily format dates according to different regional conventions.

4. Example

Suppose we want to format a date with the output format dd/MM/yyyy HH:mm:ss. We can do the following:

javascript
const date = new Date(); const day = date.getDate().toString().padStart(2, '0'); const month = (date.getMonth() + 1).toString().padStart(2, '0'); const year = date.getFullYear(); const hours = date.getHours().toString().padStart(2, '0'); const minutes = date.getMinutes().toString().padStart(2, '0'); const seconds = date.getSeconds().toString().padStart(2, '0'); const formattedDate = `${day}/${month}/${year} ${hours}:${minutes}:${seconds}`; console.log(formattedDate); // Output format like: '10/03/2023 14:20:30'

When choosing a method, consider your specific needs (e.g., whether localization is required, whether you want to introduce additional libraries, etc.). For simple requirements, the built-in Date methods may suffice. For more complex or specific formatting needs, third-party libraries or the Intl object may simplify the code.

2024年6月29日 12:07 回复

Using the dateformat library:

javascript
var dateFormat = require('dateformat'); var now = new Date(); dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");

Returns:

Saturday, June 9th, 2007, 5:46:21 PM

dateformat on npm

JSFiddle example

2024年6月29日 12:07 回复

If you require slightly less control over formatting than what is typically provided, the Date#toLocaleDateString method can be used to create standard locale-specific renderings. The locale parameter allows the application to specify the language whose formatting conventions should be used, and enables some customization of the presentation.

Key Options Examples:

  1. day: Represents the day of the month. Possible values: "numeric", "2-digit".
  2. weekday: Represents the day of the week. Possible values: "narrow", "short", "long".
  3. year: Represents the year. Possible values: "numeric", "2-digit".
  4. month: Represents the month. Possible values: "numeric", "2-digit", "narrow", "short", "long".
  5. hour: Represents the hour. Possible values: "numeric", "2-digit".
  6. minute: Represents the minute. Possible values: "numeric", "2-digit".
  7. second: Represents the second. Possible values: "numeric", "2-digit".
  8. hour12: Represents the 12-hour clock format. Accepts boolean values: true or false.

All these keys are optional. You can adjust the option values based on your requirements, which will determine the inclusion of each date-time term.

Note: If you only want to configure the options for content but still use the current locale, passing null as the first parameter will cause an error. Use undefined instead.

For Different Languages:

  1. "en-US": American English
  2. "en-GB": British English
  3. "hi-IN": Hindi
  4. "ja-JP": Japanese

You can use more language options.

Example

javascript
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; var today = new Date(); console.log(today.toLocaleDateString("en-US")); // 9/17/2016 console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016 console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016

You can also use the toLocaleString() method to achieve the same purpose. The only difference is that this function provides the time when no options are passed.

javascript
// Example 9/17/2016, 1:21:34 PM

References:

2024年6月29日 12:07 回复

如果您需要使用纯 JavaScript 快速设置日期格式,请使用getDategetMonth + 1getFullYear和:getHours``getMinutes

shell
var d = new Date(); var datestring = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes(); // 16-5-2015 9:50

或者,如果您需要用零填充:

shell
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" + d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2); // 16-05-2015 09:50
2024年6月29日 12:07 回复

你的答案