P粉2538003122023-08-24 09:32:38
If you need slightly less control over the formatting than the currently accepted answer, Date#toLocaleDateString
can be used to create a standard locale-specific rendering. The locale
and options
parameters let the application specify the language in which the formatting convention should be used, and allow some customization of rendering.
All these keys are optional. You can change the number of option values as per your requirement and this will also reflect the presence of each date time term.
Note: If you only want to configure content options but still use the current locale, passing null
for the first argument will result in an error. Please use undefined
instead.
More language options are available to you.
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 you don't pass any options.
// Example 9/17/2016, 1:21:34 PM
P粉4574458582023-08-24 00:10:33
For custom delimited date formats you must extract the date (or time)
Component from a DateTimeFormat
object (i.e. part of
ECMAScript Internationalization API) and then manually create the string
with your desired delimiter.
To do this, you can use DateTimeFormat# formatToParts
. you can
Destructuring the array, but this is not ideal since the array output depends on
regional settings:
{ // example 1 let formatter = new Intl.DateTimeFormat('en'); let example = formatter.formatToParts(); console.log(example); } { // example 2 let formatter = new Intl.DateTimeFormat('hi'); let example = formatter.formatToParts(); console.log(example); }