How to format a JavaScript date
如何将JavaScript日期对象格式化为10-Aug-2010
打印?
function formatDate(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
return day + ' ' + monthNames[monthIndex] + ' ' + year;
}
console.log(formatDate(new Date())); // show current date-time in console
Use toLocaleDateString();
The toLocaleDateString() method returns a string with a language-sensitive representation of the date portion of the date. The locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function.
The values you can passed in options for different keys:
The representation of the day.
Possible values are "numeric", "2-digit".
The representation of the weekday.
Possible values are "narrow", "short", "long".
The representation of the year.
Possible values are "numeric", "2-digit".
The representation of the month.
Possible values are "numeric", "2-digit", "narrow", "short", "long".
The representation of the hour.
Possible values are "numeric", "2-digit".
Possible values are "numeric", "2-digit".
The representation of the second.
Possible values are "numeric", 2-digit".
All these keys are optional.You can change the number of options values based on your requirements.
For different languages:
You can use more language options.
For example
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today = new Date();
console.log(today.toLocaleDateString("en-US"));
console.log(today.toLocaleDateString("en-US",options));
console.log(today.toLocaleDateString("hi-IN", options));
// Outputs will be -
9/17/2016
Saturday, September 17, 2016
शनिवार, 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
References:
For toLocaleString()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
For toLocaleDateString()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Use the date.format library:
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
http://jsfiddle.net/phZr7/1/
链接地址: http://www.djcxy.com/p/3124.html下一篇: 如何格式化JavaScript日期