In JavaScript, how can I format a date object to print as 10-Aug-2010
?
If you need slightly less control over formatting than the currently accepted answer, Date#toLocaleDateString
can be used to create standard locale-specific renderings. The locale
and options
arguments let applications specify the language whose formatting conventions should be used, and allow some customization of the rendering.
All these keys are optional. You can change the number of options values based on your requirements, and this will also reflect the presence of each date time term.
Note: If you would only like to configure the content options, but still use the current locale, passing null
for the first parameter will cause an error. Use undefined
instead.
You can use more language options.
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 for the same purpose. The only difference is this function provides the time when you don't pass any options.
// Example
9/17/2016, 1:21:34 PM