How can I format a JavaScript date object to print as 10-Aug-2010
?
如何将JavaScript日期对象格式化为10- 8 -2010?
43 个解决方案
#1
776
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
You can edit the array monthNames
to use Jan, Feb, Mar, etc..
您可以编辑该数组的月份名称,以便使用Jan、Feb、Mar等。
#2
501
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.
toLocaleDateString()方法返回一个字符串,其中包含日期部分的语言敏感表示。locales和options参数让应用程序指定应该使用格式化约定的语言,并允许定制函数的行为。
The values you can passed in options for different keys:
-
day:
The representation of the day.
Possible values are "numeric", "2-digit". - 白天:白天的表现。可能的值是“数字”,“2位”。
-
weekday:
The representation of the weekday.
Possible values are "narrow", "short", "long". - 工作日:工作日的代表。可能的值是“窄”、“短”、“长”。
-
year:
The representation of the year.
Possible values are "numeric", "2-digit". - 年度:年度代表。可能的值是“数字”,“2位”。
-
month:
The representation of the month.
Possible values are "numeric", "2-digit", "narrow", "short", "long". - 月:代表月份。可能的值是“数字”、“2位”、“窄”、“短”、“长”。
-
hour:
The representation of the hour.
Possible values are "numeric", "2-digit". - 小时:时间的表示。可能的值是“数字”,“2位”。
-
minute: The representation of the minute.
Possible values are "numeric", "2-digit". - 分钟:分钟的表示。可能的值是“数字”,“2位”。
-
second:
The representation of the second.
Possible values are "numeric", 2-digit". - 第二:第二种表现形式。可能的值是“数字”,2位数。
All these keys are optional.You can change the number of options values based on your requirements.
所有这些键都是可选的。您可以根据您的需求更改选项值的数量。
For different languages:
- "en-US": For English
- “en - us”:为英语
- "hi-IN": For Hindi
- “hi-IN”:印地语
- "ja-JP": For Japanese
- “ja-JP”:日本
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.
您还可以使用toLocaleString()方法实现相同的目的。唯一的区别是这个函数提供了不通过任何选项的时间。
// Example
9/17/2016, 1:21:34 PM
References:
For toLocaleString()
对于toLocaleString()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
For toLocaleDateString()
对于toLocaleDateString()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
#3
500
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 npm上
http://jsfiddle.net/phZr7/1/
#4
285
If you need to quickly format your date using plain JavaScript, use getDate
, getMonth + 1
, getFullYear
, getHours
and getMinutes
:
如果你需要快速格式化你的日期,使用简单的JavaScript,使用getDate, getMonth + 1, getFullYear, getHours和getMinutes:
var d = new Date();
var datestring = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();
// 16-5-2015 9:50
Or, if you need it to be padded with zeros:
或者,如果你需要用0来填充的话:
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
#5
278
Well, what I wanted was to convert today's date to a MySQL friendly date string like 2012-06-23, and to use that string as a parameter in one of my queries. The simple solution I've found is this:
我想要的是将今天的日期转换成一个MySQL友好的日期字符串,比如2012-06-23,并且在我的一个查询中使用这个字符串作为参数。我找到的简单的解决方法是:
var today = new Date().toISOString().slice(0, 10);
Keep in mind that the above solution does not take into account your timezone offset.
请记住,上面的解决方案没有考虑到您的时区偏移。
You might consider using this function instead:
你可以考虑使用这个函数:
function toJSONLocal (date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
This will give you the correct date in case you are executing this code around the start/end of the day.
这将给您正确的日期,以防您在一天的开始/结束时执行此代码。
- Example: http://jsfiddle.net/simo/sapuhzmm/
- 例如:http://jsfiddle.net/simo/sapuhzmm/
- Date.toISOString
- Date.toISOString
- Date.toJSON
- Date.toJSON
- String.slice
- String.slice
#6
149
If you are already using jQuery UI in your project you could do it this way:
如果您已经在项目中使用jQuery UI,您可以这样做:
var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));
// formatted will be 'Jul 8, 2014'
Some datepicker date format options to play with are available here.
一些datepicker日期格式选项可以在这里使用。
#7
109
I think you can just use the non-standard Date method toLocaleFormat(formatString)
我认为您可以使用非标准日期方法toLocaleFormat(formatString)
formatString: A format string in the same format expected by the strftime()
function in C.
格式字符串:在C语言中,strftime()函数所期望的格式字符串。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
References:
引用:
- tolocaleformat
- tolocaleformat
- strftime
- strftime
#8
83
Plain JavaScript is the best pick for small onetimers.
简单的JavaScript是小型onetimer的最佳选择。
On the other hand, if you need more date stuff, MomentJS is a great solution.
另一方面,如果您需要更多的日期内容,MomentJS是一个很好的解决方案。
For example:
例如:
moment().format('YYYY-MM-DD HH:m:s'); // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 11 hours ago
moment().endOf('day').fromNow(); // in 13 hours
#9
83
Custom formatting function:
For fixed formats, a simple function make the job. The following example generates the international format YYYY-MM-DD:
对于固定格式,一个简单的函数就能完成任务。下面的例子生成了国际格式YYYY-MM-DD:
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1; //Month from 0 to 11
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5
The OP format may be generated like:
OP格式可以是:
function dateToYMD(date) {
var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var d = date.getDate();
var m = strArray[date.getMonth()];
var y = date.getFullYear();
return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5
Note: It is, however, usually not a good idea to extend the JavaScript standard libraries (e.g. by adding this function to the prototype of Date).
注意:扩展JavaScript标准库通常不是一个好主意(例如,将这个函数添加到日期的原型中)。
A more advanced function could generate configurable output based on a format parameter.
一个更高级的函数可以根据格式参数生成可配置的输出。
If to write a formatting function is too long, there are plenty of libraries around which does it. Some other answers already enumerate them. But increasing dependencies also has it counter-part.
如果要编写一个格式化函数太长,那么就有大量的库。一些其他的答案已经列举出来了。但是越来越多的依赖关系也起到了相反的作用。
Standard ECMAScript formatting functions:
Since more recent versions of ECMAScript, the Date
class has some specific formatting functions:
由于ECMAScript的最新版本,Date类具有一些特定的格式化功能:
toDateString: Implementation dependent, show only the date.
toDateString:实现依赖,只显示日期。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.todatestring
new Date().toDateString(); // e.g. "Fri Nov 11 2016"
toISOString: Show ISO 8601 date and time.
toISOString:显示ISO 8601日期和时间。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.toisostring
new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"
toJSON: Stringifier for JSON.
toJSON:Stringifier JSON。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tojson
new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"
toLocaleDateString: Implementation dependent, a date in locale format.
toLocaleDateString:实现依赖,日期的地区格式。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tolocaledatestring
new Date().toLocaleDateString(); // e.g. "21/11/2016"
toLocaleString: Implementation dependent, a date&time in locale format.
toLocaleString:实现依赖,一个日期和时间的地区格式。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tolocalestring
new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"
toLocaleTimeString: Implementation dependent, a time in locale format.
toLocaleTimeString:实现依赖,一种语言环境格式的时间。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tolocaletimestring
new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"
toString: Generic toString for Date.
toString:用于日期的通用字符串。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tostring
new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"
Note: it is possible to generate custom output out of those formatting >
注意:可以从这些格式化>中生成自定义输出。
new Date().toISOString().slice(0,10); //return YYYY-MM-DD
Examples snippets:
例子代码片段:
console.log("1) "+ new Date().toDateString());
console.log("2) "+ new Date().toISOString());
console.log("3) "+ new Date().toJSON());
console.log("4) "+ new Date().toLocaleDateString());
console.log("5) "+ new Date().toLocaleString());
console.log("6) "+ new Date().toLocaleTimeString());
console.log("7) "+ new Date().toString());
console.log("8) "+ new Date().toISOString().slice(0,10));
#10
79
In modern browsers (*), you can just do this:
在现代浏览器中(*),您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
Output if executed today (january 24ᵗʰ, 2016):
今天(2016年1月24日)执行的输出:
'24-Jan-2016'
(*) According to MDN, "modern browsers" means Chrome 24+, Firefox 29+, Internet Explorer 11, Edge 12+, Opera 15+ & Safari nightly build.
(*)根据MDN,“现代浏览器”意味着Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间构建。
#11
47
You should have a look at date.js. It adds many convenient helpers for working with dates, for example, in your case:
你应该看看date.j。它为处理日期添加了许多方便的助手,例如,在您的案例中:
var date = Date.parse('2010-08-10');
console.log(date.toString('dd-MMM-yyyy'));
Getting started: http://www.datejs.com/2007/11/27/getting-started-with-datejs/
开始:http://www.datejs.com/2007/11/27/getting-started-with-datejs/
#12
29
@Sébastien -- alternative all browser support
@Sebastien——替代所有浏览器支持。
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
#13
29
I can get your requested format in one line using no libraries and no Date methods, just regex:
我可以在一行中使用没有库和日期的方法来获得请求的格式,只是regex:
var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')
Update: As @RobG pointed out, the output of Date.prototype.toString() is implementation-dependent. So, use with caution and modify if necessary for your implementations if you use this solution. In my testing, this works reliably in North America where the major browsers (Chrome, Safari, Firefox and IE) all return the same string format.
更新:正如@RobG指出的,Date.prototype.toString()的输出是依赖于实现的。因此,如果您使用此解决方案,请谨慎使用并修改您的实现。在我的测试中,这在北美很可靠,主要的浏览器(Chrome, Safari, Firefox和IE)都返回相同的字符串格式。
#14
15
Here's is some code I just wrote to handle the date formatting for a project I'm working on. It mimics the PHP date formatting functionality to suit my needs. Feel free to use it, it's just extending the already existing Date() object. This may not be the most elegant solution but it's working for my needs.
下面是我写的一些代码,用来处理我正在开发的项目的日期格式。它模仿PHP的日期格式功能以满足我的需要。可以随意使用它,它只是扩展已经存在的Date()对象。这可能不是最优雅的解决方案,但它能满足我的需求。
var d = new Date();
d_string = d.format("m/d/Y h:i:s");
/**************************************
* Date class extension
*
*/
// Provide month names
Date.prototype.getMonthName = function(){
var month_names = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
return month_names[this.getMonth()];
}
// Provide month abbreviation
Date.prototype.getMonthAbbr = function(){
var month_abbrs = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
return month_abbrs[this.getMonth()];
}
// Provide full day of week name
Date.prototype.getDayFull = function(){
var days_full = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
return days_full[this.getDay()];
};
// Provide full day of week name
Date.prototype.getDayAbbr = function(){
var days_abbr = [
'Sun',
'Mon',
'Tue',
'Wed',
'Thur',
'Fri',
'Sat'
];
return days_abbr[this.getDay()];
};
// Provide the day of year 1-365
Date.prototype.getDayOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
};
// Provide the day suffix (st,nd,rd,th)
Date.prototype.getDaySuffix = function() {
var d = this.getDate();
var sfx = ["th","st","nd","rd"];
var val = d%100;
return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
};
// Provide Week of Year
Date.prototype.getWeekOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
// Provide if it is a leap year or not
Date.prototype.isLeapYear = function(){
var yr = this.getFullYear();
if ((parseInt(yr)%4) == 0){
if (parseInt(yr)%100 == 0){
if (parseInt(yr)%400 != 0){
return false;
}
if (parseInt(yr)%400 == 0){
return true;
}
}
if (parseInt(yr)%100 != 0){
return true;
}
}
if ((parseInt(yr)%4) != 0){
return false;
}
};
// Provide Number of Days in a given month
Date.prototype.getMonthDayCount = function() {
var month_day_counts = [
31,
this.isLeapYear() ? 29 : 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
return month_day_counts[this.getMonth()];
}
// format provided date into this.format format
Date.prototype.format = function(dateFormat){
// break apart format string into array of characters
dateFormat = dateFormat.split("");
var date = this.getDate(),
month = this.getMonth(),
hours = this.getHours(),
minutes = this.getMinutes(),
seconds = this.getSeconds();
// get all date properties ( based on PHP date object functionality )
var date_props = {
d: date < 10 ? '0'+date : date,
D: this.getDayAbbr(),
j: this.getDate(),
l: this.getDayFull(),
S: this.getDaySuffix(),
w: this.getDay(),
z: this.getDayOfYear(),
W: this.getWeekOfYear(),
F: this.getMonthName(),
m: month < 10 ? '0'+(month+1) : month+1,
M: this.getMonthAbbr(),
n: month+1,
t: this.getMonthDayCount(),
L: this.isLeapYear() ? '1' : '0',
Y: this.getFullYear(),
y: this.getFullYear()+''.substring(2,4),
a: hours > 12 ? 'pm' : 'am',
A: hours > 12 ? 'PM' : 'AM',
g: hours % 12 > 0 ? hours % 12 : 12,
G: hours > 0 ? hours : "12",
h: hours % 12 > 0 ? hours % 12 : 12,
H: hours,
i: minutes < 10 ? '0' + minutes : minutes,
s: seconds < 10 ? '0' + seconds : seconds
};
// loop through format array of characters and add matching data else add the format character (:,/, etc.)
var date_string = "";
for(var i=0;i<dateFormat.length;i++){
var f = dateFormat[i];
if(f.match(/[a-zA-Z]/g)){
date_string += date_props[f] ? date_props[f] : '';
} else {
date_string += f;
}
}
return date_string;
};
/*
*
* END - Date class extension
*
************************************/
#15
14
If you are using jQuery UI in your code, there is an inbuilt function called formatDate()
. I am using it this way to format today's date:
如果您在代码中使用jQuery UI,那么有一个inbuild函数,称为formatDate()。我用这种方法来格式化今天的日期:
var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);
You can see many other examples of formatting date in the jQuery UI documentation.
您可以在jQuery UI文档中看到许多格式化日期的其他示例。
#16
12
Using a ECMAScript 6 string template:
使用ECMAScript 6字符串模板:
let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
If you need to change the delimiters:
如果需要更改分隔符:
const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
#17
11
JavaScript solution without using any external libraries:
不使用任何外部库的JavaScript解决方案:
var now = new Date()
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
var formattedDate = now.getDate()+"-"+months[now.getMonth()]+"-"+now.getFullYear()
alert(formattedDate)
#18
11
We have lots of solutions for this, but I think the best of them is Moment.js. So I personally suggest to use Moment.js for date and time operations.
我们有很多解决方案,但我认为最好的解决方案是瞬间。所以我个人建议使用Moment。用于日期和时间操作。
console.log(moment().format('DD-MMM-YYYY'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
#19
9
This is how I implemented for my npm plugins
这是我为我的npm插件实现的方式。
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var Days = [
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
];
var formatDate = function(dt,format){
format = format.replace('ss', pad(dt.getSeconds(),2));
format = format.replace('s', dt.getSeconds());
format = format.replace('dd', pad(dt.getDate(),2));
format = format.replace('d', dt.getDate());
format = format.replace('mm', pad(dt.getMinutes(),2));
format = format.replace('m', dt.getMinutes());
format = format.replace('MMMM', monthNames[dt.getMonth()]);
format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
format = format.replace('MM', pad(dt.getMonth()+1,2));
format = format.replace(/M(?![ao])/, dt.getMonth()+1);
format = format.replace('DD', Days[dt.getDay()]);
format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
format = format.replace('yyyy', dt.getFullYear());
format = format.replace('YYYY', dt.getFullYear());
format = format.replace('yy', (dt.getFullYear()+"").substring(2));
format = format.replace('YY', (dt.getFullYear()+"").substring(2));
format = format.replace('HH', pad(dt.getHours(),2));
format = format.replace('H', dt.getHours());
return format;
}
pad = function(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
#20
8
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
#21
8
A useful and flexible way for formatting the DateTimes in JavaScript is Intl.DateTimeFormat
:
在JavaScript中格式化DateTimes的一种有用且灵活的方法是Intl.DateTimeFormat:
var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));
Result Is: "12-Oct-2017"
结果是:“12 - 10月- 2017”
The date and time formats can be customized using the options argument.
可以使用选项参数定制日期和时间格式。
The Intl.DateTimeFormat
object is a constructor for objects that enable language sensitive date and time formatting.
Intl。DateTimeFormat对象是用于支持语言敏感日期和时间格式的对象的构造函数。
Syntax
语法
new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
Parameters
参数
locales
地区
Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. The following Unicode extension keys are allowed:
可选的。一个带有BCP 47语言标记的字符串,或者是这样的字符串数组。对于locales参数的一般形式和解释,请参见Intl页面。允许下列Unicode扩展键:
nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".
Options
选项
Optional. An object with some or all of the following properties:
可选的。一个具有以下属性的对象:
localeMatcher
localeMatcher
The locale matching algorithm to use. Possible values are "lookup"
and "best fit"
; the default is "best fit"
. For information about this option, see the Intl page.
区域匹配算法的使用。可能的值是“查找”和“最佳匹配”;默认值是“最佳匹配”。有关此选项的信息,请参见Intl页面。
timeZone
时区
The time zone to use. The only value implementations must recognize is "UTC"
; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai"
, "Asia/Kolkata"
, "America/New_York"
.
使用的时区。惟一的值实现必须识别为“UTC”;默认值是运行时的默认时区。实现还可以识别IANA时区数据库的时区名称,如“Asia/Shanghai”、“Asia/Kolkata”、“America/New_York”。
hour12
hour12
Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true
and false
; the default is locale dependent.
是否使用12小时的时间(相对于24小时的时间)。可能的值是真和假的;默认情况下是语言环境相关的。
formatMatcher
formatMatcher
The format matching algorithm to use. Possible values are "basic"
and "best fit"
; the default is "best fit"
. See the following paragraphs for information about the use of this property.
格式匹配算法的使用。可能的值是“基本的”和“最合适的”;默认值是“最佳匹配”。有关此属性的使用情况,请参阅以下各段。
The following properties describe the date-time components to use in formatted output and their desired representations. Implementations are required to support at least the following subsets:
下面的属性描述了在格式化输出中使用的日期时间组件及其所需的表示。实现需要至少支持以下子集:
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. Two algorithms are available for this negotiation and selected by the formatMatcher property: A fully specified "basic"
algorithm and an implementation dependent "best fit" algorithm.
实现可能支持其他子集,并且请求将与所有可用的子集合表示组合进行协商,以找到最佳匹配。两种算法可用于此协商,并由formatMatcher属性选择:完全指定的“基本”算法和依赖于“最佳匹配”算法的实现。
weekday
工作日
The representation of the weekday. Possible values are "narrow"
, "short"
, "long"
.
工作日的代表。可能的值是“窄”、“短”、“长”。
era
时代
The representation of the era. Possible values are "narrow"
, "short"
, "long"
.
时代的代表。可能的值是“窄”、“短”、“长”。
year
一年
The representation of the year. Possible values are "numeric"
, "2-digit"
.
年度代表。可能的值是“数字”,“2位”。
month
月
The representation of the month. Possible values are "numeric"
, "2-digit"
, "narrow"
, "short"
, "long"
.
这个月的代表。可能的值是“数字”、“2位”、“窄”、“短”、“长”。
day
一天
The representation of the day. Possible values are "numeric"
, "2-digit"
.
这一天的代表。可能的值是“数字”,“2位”。
hour
小时
The representation of the hour. Possible values are "numeric"
, "2-digit"
.
一小时的代表。可能的值是“数字”,“2位”。
minute
一分钟
The representation of the minute. Possible values are "numeric"
, "2-digit"
.
一分钟的代表。可能的值是“数字”,“2位”。
second
第二个
The representation of the second. Possible values are "numeric"
, "2-digit"
.
第二个的表示。可能的值是“数字”,“2位”。
timeZoneName
timeZoneName
The representation of the time zone name. Possible values are "short"
, "long"
. The default value for each date-time component property is undefined, but if all component properties are undefined, then the year, month and day are assumed to be "numeric"
.
时区名称的表示。可能的值是“短”、“长”。每个日期时间组件属性的默认值都是未定义的,但是如果所有组件属性都未定义,则假定年、月和日为“数值”。
检查在线
更多的细节
#22
8
new Date().toLocaleDateString()
// "3/21/2018"
More documentation at developer.mozilla.org
更多文档:developer.mozilla.org
#23
7
Sugar.js has excellent extensions to the Date object, including a Date.format method.
糖。js对Date对象有很好的扩展,包括一个日期。格式的方法。
Examples from the documentation:
从文档的例子:
Date.create().format('{Weekday} {Month} {dd}, {yyyy}');
Date.create().format('{12hr}:{mm}{tt}')
#24
7
OK, we have got something called Intl which is very useful for formatting a date in JavaScript:
好的,我们有一个叫做Intl的东西它对于格式化JavaScript的日期非常有用:
Your date as below:
你的日期如下:
var date = '10/8/2010';
And you change to Date by using new Date() like below:
你可以使用下面的新日期()来更改日期:
date = new Date(date);
And now you can format it any way you like using a list of locales like below:
现在你可以用下面的方式来格式化你喜欢的地方:
date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010"
date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010"
date = new Intl.DateTimeFormat('ar-EG').format(date); // Arabic date format: "٨/١٠/٢٠١٠"
If you exactly want the format you mentioned above, you can do:
如果你确实想要你上面提到的格式,你可以:
date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');
And the result is going to be:
结果是:
"10-Aug-2010"
For more details about ECMAScript Internationalization API (Intl), visit here.
有关ECMAScript国际化API (Intl)的更多细节,请访问这里。
#25
4
Try this:
试试这个:
function init(){
var d = new Date();
var day = d.getDate();
var x = d.toDateString().substr(4, 3);
var year = d.getFullYear();
document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;
}
window.onload = init;
<div id="mydate"></div>
#26
3
Here is a script that does exactly what you want
这里有一个脚本,它可以精确地执行您想要的操作。
https://github.com/UziTech/js-date-format
https://github.com/UziTech/js-date-format
var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));
#27
3
Inspired by JD Smith's marvellous regular expression solution, I suddenly had this head-splitting idea:
受到JD Smith绝妙的正则表达式解决方案的启发,我突然想到了一个令人头疼的想法:
var D = Date().toString().split(" ");
document.getElementById("demo").innerHTML = D[2] + "-" + D[1] + "-" + D[3];
#28
#29
2
I use the following. It is simple and works fine.
我使用下面的。它很简单,也很好用。
var dtFormat = require('dtformat');
var today = new Date();
dtFormat(today, "dddd, mmmm dS, yyyy, h:MM:ss TT");
Or this:
或:
var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
#30
2
DateFormatter.formatDate(new Date(2010,7,10), 'DD-MMM-YYYY')
dateformat。formatDate(新日期(2010、7、10)、“DD-MMM-YYYY”)
=>10-Aug-2010
= > 10 - 8月- 2010
DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
dateformat。formatDate(新日期(),“YYYY-MM-DD HH:mm:ss”)
=>2017-11-22 19:52:37
= > 2017-11-22 19:52:37
DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A')
dateformat。格式日期(新日期(2005年,1,2,3,4,5),DD DDD DDDD, mmmmm, yyyyy, h hh, MMM, s ss, a ')
=>2 02 Wed Wednesday, 2 02 Feb February, 05 2005, 3 03 3 03, 4 04, 5 05, am AM
= >202星期三,2月2日,2005年2月5日,03 03 3 03,4 04,5 05,am。
var DateFormatter = {
monthNames: [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
],
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
formatDate: function (date, format) {
var self = this;
format = self.getProperDigits(format, /d+/gi, date.getDate());
format = self.getProperDigits(format, /M+/g, date.getMonth() + 1);
format = format.replace(/y+/gi, function (y) {
var len = y.length;
var year = date.getFullYear();
if (len == 2)
return (year + "").slice(-2);
else if (len == 4)
return year;
return y;
})
format = self.getProperDigits(format, /H+/g, date.getHours());
format = self.getProperDigits(format, /h+/g, self.getHours12(date.getHours()));
format = self.getProperDigits(format, /m+/g, date.getMinutes());
format = self.getProperDigits(format, /s+/gi, date.getSeconds());
format = format.replace(/a/ig, function (a) {
var amPm = self.getAmPm(date.getHours())
if (a === 'A')
return amPm.toUpperCase();
return amPm;
})
format = self.getFullOr3Letters(format, /d+/gi, self.dayNames, date.getDay())
format = self.getFullOr3Letters(format, /M+/g, self.monthNames, date.getMonth())
return format;
},
getProperDigits: function (format, regex, value) {
return format.replace(regex, function (m) {
var length = m.length;
if (length == 1)
return value;
else if (length == 2)
return ('0' + value).slice(-2);
return m;
})
},
getHours12: function (hours) {
// https://*.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method
return (hours + 24) % 12 || 12;
},
getAmPm: function (hours) {
// https://*.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format
return hours >= 12 ? 'pm' : 'am';
},
getFullOr3Letters: function (format, regex, nameArray, value) {
return format.replace(regex, function (s) {
var len = s.length;
if (len == 3)
return nameArray[value].substr(0, 3);
else if (len == 4)
return nameArray[value];
return s;
})
}
}
console.log(DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'));
console.log(DateFormatter.formatDate(new Date(), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
console.log(DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
Format description was take Ionic Framework (does not support Z
,UTC Timezone Offset)
格式描述采用Ionic框架(不支持Z,UTC时区偏移)
Not thoroughly tested
没有彻底的测试
#1
776
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
You can edit the array monthNames
to use Jan, Feb, Mar, etc..
您可以编辑该数组的月份名称,以便使用Jan、Feb、Mar等。
#2
501
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.
toLocaleDateString()方法返回一个字符串,其中包含日期部分的语言敏感表示。locales和options参数让应用程序指定应该使用格式化约定的语言,并允许定制函数的行为。
The values you can passed in options for different keys:
-
day:
The representation of the day.
Possible values are "numeric", "2-digit". - 白天:白天的表现。可能的值是“数字”,“2位”。
-
weekday:
The representation of the weekday.
Possible values are "narrow", "short", "long". - 工作日:工作日的代表。可能的值是“窄”、“短”、“长”。
-
year:
The representation of the year.
Possible values are "numeric", "2-digit". - 年度:年度代表。可能的值是“数字”,“2位”。
-
month:
The representation of the month.
Possible values are "numeric", "2-digit", "narrow", "short", "long". - 月:代表月份。可能的值是“数字”、“2位”、“窄”、“短”、“长”。
-
hour:
The representation of the hour.
Possible values are "numeric", "2-digit". - 小时:时间的表示。可能的值是“数字”,“2位”。
-
minute: The representation of the minute.
Possible values are "numeric", "2-digit". - 分钟:分钟的表示。可能的值是“数字”,“2位”。
-
second:
The representation of the second.
Possible values are "numeric", 2-digit". - 第二:第二种表现形式。可能的值是“数字”,2位数。
All these keys are optional.You can change the number of options values based on your requirements.
所有这些键都是可选的。您可以根据您的需求更改选项值的数量。
For different languages:
- "en-US": For English
- “en - us”:为英语
- "hi-IN": For Hindi
- “hi-IN”:印地语
- "ja-JP": For Japanese
- “ja-JP”:日本
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.
您还可以使用toLocaleString()方法实现相同的目的。唯一的区别是这个函数提供了不通过任何选项的时间。
// Example
9/17/2016, 1:21:34 PM
References:
For toLocaleString()
对于toLocaleString()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
For toLocaleDateString()
对于toLocaleDateString()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
#3
500
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 npm上
http://jsfiddle.net/phZr7/1/
#4
285
If you need to quickly format your date using plain JavaScript, use getDate
, getMonth + 1
, getFullYear
, getHours
and getMinutes
:
如果你需要快速格式化你的日期,使用简单的JavaScript,使用getDate, getMonth + 1, getFullYear, getHours和getMinutes:
var d = new Date();
var datestring = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();
// 16-5-2015 9:50
Or, if you need it to be padded with zeros:
或者,如果你需要用0来填充的话:
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
#5
278
Well, what I wanted was to convert today's date to a MySQL friendly date string like 2012-06-23, and to use that string as a parameter in one of my queries. The simple solution I've found is this:
我想要的是将今天的日期转换成一个MySQL友好的日期字符串,比如2012-06-23,并且在我的一个查询中使用这个字符串作为参数。我找到的简单的解决方法是:
var today = new Date().toISOString().slice(0, 10);
Keep in mind that the above solution does not take into account your timezone offset.
请记住,上面的解决方案没有考虑到您的时区偏移。
You might consider using this function instead:
你可以考虑使用这个函数:
function toJSONLocal (date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
This will give you the correct date in case you are executing this code around the start/end of the day.
这将给您正确的日期,以防您在一天的开始/结束时执行此代码。
- Example: http://jsfiddle.net/simo/sapuhzmm/
- 例如:http://jsfiddle.net/simo/sapuhzmm/
- Date.toISOString
- Date.toISOString
- Date.toJSON
- Date.toJSON
- String.slice
- String.slice
#6
149
If you are already using jQuery UI in your project you could do it this way:
如果您已经在项目中使用jQuery UI,您可以这样做:
var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));
// formatted will be 'Jul 8, 2014'
Some datepicker date format options to play with are available here.
一些datepicker日期格式选项可以在这里使用。
#7
109
I think you can just use the non-standard Date method toLocaleFormat(formatString)
我认为您可以使用非标准日期方法toLocaleFormat(formatString)
formatString: A format string in the same format expected by the strftime()
function in C.
格式字符串:在C语言中,strftime()函数所期望的格式字符串。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
References:
引用:
- tolocaleformat
- tolocaleformat
- strftime
- strftime
#8
83
Plain JavaScript is the best pick for small onetimers.
简单的JavaScript是小型onetimer的最佳选择。
On the other hand, if you need more date stuff, MomentJS is a great solution.
另一方面,如果您需要更多的日期内容,MomentJS是一个很好的解决方案。
For example:
例如:
moment().format('YYYY-MM-DD HH:m:s'); // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow(); // 11 hours ago
moment().endOf('day').fromNow(); // in 13 hours
#9
83
Custom formatting function:
For fixed formats, a simple function make the job. The following example generates the international format YYYY-MM-DD:
对于固定格式,一个简单的函数就能完成任务。下面的例子生成了国际格式YYYY-MM-DD:
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1; //Month from 0 to 11
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5
The OP format may be generated like:
OP格式可以是:
function dateToYMD(date) {
var strArray=['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var d = date.getDate();
var m = strArray[date.getMonth()];
var y = date.getFullYear();
return '' + (d <= 9 ? '0' + d : d) + '-' + m + '-' + y;
}
console.log(dateToYMD(new Date(2017,10,5))); // Nov 5
Note: It is, however, usually not a good idea to extend the JavaScript standard libraries (e.g. by adding this function to the prototype of Date).
注意:扩展JavaScript标准库通常不是一个好主意(例如,将这个函数添加到日期的原型中)。
A more advanced function could generate configurable output based on a format parameter.
一个更高级的函数可以根据格式参数生成可配置的输出。
If to write a formatting function is too long, there are plenty of libraries around which does it. Some other answers already enumerate them. But increasing dependencies also has it counter-part.
如果要编写一个格式化函数太长,那么就有大量的库。一些其他的答案已经列举出来了。但是越来越多的依赖关系也起到了相反的作用。
Standard ECMAScript formatting functions:
Since more recent versions of ECMAScript, the Date
class has some specific formatting functions:
由于ECMAScript的最新版本,Date类具有一些特定的格式化功能:
toDateString: Implementation dependent, show only the date.
toDateString:实现依赖,只显示日期。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.todatestring
new Date().toDateString(); // e.g. "Fri Nov 11 2016"
toISOString: Show ISO 8601 date and time.
toISOString:显示ISO 8601日期和时间。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.toisostring
new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"
toJSON: Stringifier for JSON.
toJSON:Stringifier JSON。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tojson
new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"
toLocaleDateString: Implementation dependent, a date in locale format.
toLocaleDateString:实现依赖,日期的地区格式。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tolocaledatestring
new Date().toLocaleDateString(); // e.g. "21/11/2016"
toLocaleString: Implementation dependent, a date&time in locale format.
toLocaleString:实现依赖,一个日期和时间的地区格式。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tolocalestring
new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"
toLocaleTimeString: Implementation dependent, a time in locale format.
toLocaleTimeString:实现依赖,一种语言环境格式的时间。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tolocaletimestring
new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"
toString: Generic toString for Date.
toString:用于日期的通用字符串。
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring
http://www.ecma-international.org/ecma-262/7.0/index.html sec-date.prototype.tostring
new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"
Note: it is possible to generate custom output out of those formatting >
注意:可以从这些格式化>中生成自定义输出。
new Date().toISOString().slice(0,10); //return YYYY-MM-DD
Examples snippets:
例子代码片段:
console.log("1) "+ new Date().toDateString());
console.log("2) "+ new Date().toISOString());
console.log("3) "+ new Date().toJSON());
console.log("4) "+ new Date().toLocaleDateString());
console.log("5) "+ new Date().toLocaleString());
console.log("6) "+ new Date().toLocaleTimeString());
console.log("7) "+ new Date().toString());
console.log("8) "+ new Date().toISOString().slice(0,10));
#10
79
In modern browsers (*), you can just do this:
在现代浏览器中(*),您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
Output if executed today (january 24ᵗʰ, 2016):
今天(2016年1月24日)执行的输出:
'24-Jan-2016'
(*) According to MDN, "modern browsers" means Chrome 24+, Firefox 29+, Internet Explorer 11, Edge 12+, Opera 15+ & Safari nightly build.
(*)根据MDN,“现代浏览器”意味着Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间构建。
#11
47
You should have a look at date.js. It adds many convenient helpers for working with dates, for example, in your case:
你应该看看date.j。它为处理日期添加了许多方便的助手,例如,在您的案例中:
var date = Date.parse('2010-08-10');
console.log(date.toString('dd-MMM-yyyy'));
Getting started: http://www.datejs.com/2007/11/27/getting-started-with-datejs/
开始:http://www.datejs.com/2007/11/27/getting-started-with-datejs/
#12
29
@Sébastien -- alternative all browser support
@Sebastien——替代所有浏览器支持。
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
#13
29
I can get your requested format in one line using no libraries and no Date methods, just regex:
我可以在一行中使用没有库和日期的方法来获得请求的格式,只是regex:
var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')
Update: As @RobG pointed out, the output of Date.prototype.toString() is implementation-dependent. So, use with caution and modify if necessary for your implementations if you use this solution. In my testing, this works reliably in North America where the major browsers (Chrome, Safari, Firefox and IE) all return the same string format.
更新:正如@RobG指出的,Date.prototype.toString()的输出是依赖于实现的。因此,如果您使用此解决方案,请谨慎使用并修改您的实现。在我的测试中,这在北美很可靠,主要的浏览器(Chrome, Safari, Firefox和IE)都返回相同的字符串格式。
#14
15
Here's is some code I just wrote to handle the date formatting for a project I'm working on. It mimics the PHP date formatting functionality to suit my needs. Feel free to use it, it's just extending the already existing Date() object. This may not be the most elegant solution but it's working for my needs.
下面是我写的一些代码,用来处理我正在开发的项目的日期格式。它模仿PHP的日期格式功能以满足我的需要。可以随意使用它,它只是扩展已经存在的Date()对象。这可能不是最优雅的解决方案,但它能满足我的需求。
var d = new Date();
d_string = d.format("m/d/Y h:i:s");
/**************************************
* Date class extension
*
*/
// Provide month names
Date.prototype.getMonthName = function(){
var month_names = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
return month_names[this.getMonth()];
}
// Provide month abbreviation
Date.prototype.getMonthAbbr = function(){
var month_abbrs = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
return month_abbrs[this.getMonth()];
}
// Provide full day of week name
Date.prototype.getDayFull = function(){
var days_full = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
return days_full[this.getDay()];
};
// Provide full day of week name
Date.prototype.getDayAbbr = function(){
var days_abbr = [
'Sun',
'Mon',
'Tue',
'Wed',
'Thur',
'Fri',
'Sat'
];
return days_abbr[this.getDay()];
};
// Provide the day of year 1-365
Date.prototype.getDayOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((this - onejan) / 86400000);
};
// Provide the day suffix (st,nd,rd,th)
Date.prototype.getDaySuffix = function() {
var d = this.getDate();
var sfx = ["th","st","nd","rd"];
var val = d%100;
return (sfx[(val-20)%10] || sfx[val] || sfx[0]);
};
// Provide Week of Year
Date.prototype.getWeekOfYear = function() {
var onejan = new Date(this.getFullYear(),0,1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);
}
// Provide if it is a leap year or not
Date.prototype.isLeapYear = function(){
var yr = this.getFullYear();
if ((parseInt(yr)%4) == 0){
if (parseInt(yr)%100 == 0){
if (parseInt(yr)%400 != 0){
return false;
}
if (parseInt(yr)%400 == 0){
return true;
}
}
if (parseInt(yr)%100 != 0){
return true;
}
}
if ((parseInt(yr)%4) != 0){
return false;
}
};
// Provide Number of Days in a given month
Date.prototype.getMonthDayCount = function() {
var month_day_counts = [
31,
this.isLeapYear() ? 29 : 28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
return month_day_counts[this.getMonth()];
}
// format provided date into this.format format
Date.prototype.format = function(dateFormat){
// break apart format string into array of characters
dateFormat = dateFormat.split("");
var date = this.getDate(),
month = this.getMonth(),
hours = this.getHours(),
minutes = this.getMinutes(),
seconds = this.getSeconds();
// get all date properties ( based on PHP date object functionality )
var date_props = {
d: date < 10 ? '0'+date : date,
D: this.getDayAbbr(),
j: this.getDate(),
l: this.getDayFull(),
S: this.getDaySuffix(),
w: this.getDay(),
z: this.getDayOfYear(),
W: this.getWeekOfYear(),
F: this.getMonthName(),
m: month < 10 ? '0'+(month+1) : month+1,
M: this.getMonthAbbr(),
n: month+1,
t: this.getMonthDayCount(),
L: this.isLeapYear() ? '1' : '0',
Y: this.getFullYear(),
y: this.getFullYear()+''.substring(2,4),
a: hours > 12 ? 'pm' : 'am',
A: hours > 12 ? 'PM' : 'AM',
g: hours % 12 > 0 ? hours % 12 : 12,
G: hours > 0 ? hours : "12",
h: hours % 12 > 0 ? hours % 12 : 12,
H: hours,
i: minutes < 10 ? '0' + minutes : minutes,
s: seconds < 10 ? '0' + seconds : seconds
};
// loop through format array of characters and add matching data else add the format character (:,/, etc.)
var date_string = "";
for(var i=0;i<dateFormat.length;i++){
var f = dateFormat[i];
if(f.match(/[a-zA-Z]/g)){
date_string += date_props[f] ? date_props[f] : '';
} else {
date_string += f;
}
}
return date_string;
};
/*
*
* END - Date class extension
*
************************************/
#15
14
If you are using jQuery UI in your code, there is an inbuilt function called formatDate()
. I am using it this way to format today's date:
如果您在代码中使用jQuery UI,那么有一个inbuild函数,称为formatDate()。我用这种方法来格式化今天的日期:
var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);
You can see many other examples of formatting date in the jQuery UI documentation.
您可以在jQuery UI文档中看到许多格式化日期的其他示例。
#16
12
Using a ECMAScript 6 string template:
使用ECMAScript 6字符串模板:
let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
If you need to change the delimiters:
如果需要更改分隔符:
const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
#17
11
JavaScript solution without using any external libraries:
不使用任何外部库的JavaScript解决方案:
var now = new Date()
months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
var formattedDate = now.getDate()+"-"+months[now.getMonth()]+"-"+now.getFullYear()
alert(formattedDate)
#18
11
We have lots of solutions for this, but I think the best of them is Moment.js. So I personally suggest to use Moment.js for date and time operations.
我们有很多解决方案,但我认为最好的解决方案是瞬间。所以我个人建议使用Moment。用于日期和时间操作。
console.log(moment().format('DD-MMM-YYYY'));
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
#19
9
This is how I implemented for my npm plugins
这是我为我的npm插件实现的方式。
var monthNames = [
"January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
];
var Days = [
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"
];
var formatDate = function(dt,format){
format = format.replace('ss', pad(dt.getSeconds(),2));
format = format.replace('s', dt.getSeconds());
format = format.replace('dd', pad(dt.getDate(),2));
format = format.replace('d', dt.getDate());
format = format.replace('mm', pad(dt.getMinutes(),2));
format = format.replace('m', dt.getMinutes());
format = format.replace('MMMM', monthNames[dt.getMonth()]);
format = format.replace('MMM', monthNames[dt.getMonth()].substring(0,3));
format = format.replace('MM', pad(dt.getMonth()+1,2));
format = format.replace(/M(?![ao])/, dt.getMonth()+1);
format = format.replace('DD', Days[dt.getDay()]);
format = format.replace(/D(?!e)/, Days[dt.getDay()].substring(0,3));
format = format.replace('yyyy', dt.getFullYear());
format = format.replace('YYYY', dt.getFullYear());
format = format.replace('yy', (dt.getFullYear()+"").substring(2));
format = format.replace('YY', (dt.getFullYear()+"").substring(2));
format = format.replace('HH', pad(dt.getHours(),2));
format = format.replace('H', dt.getHours());
return format;
}
pad = function(n, width, z) {
z = z || '0';
n = n + '';
return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}
#20
8
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
#21
8
A useful and flexible way for formatting the DateTimes in JavaScript is Intl.DateTimeFormat
:
在JavaScript中格式化DateTimes的一种有用且灵活的方法是Intl.DateTimeFormat:
var date = new Date();
var options = { year: 'numeric', month: 'short', day: '2-digit'};
var _resultDate = new Intl.DateTimeFormat('en-GB', options).format(date);
// The _resultDate is: "12 Oct 2017"
// Replace all spaces with - and then log it.
console.log(_resultDate.replace(/ /g,'-'));
Result Is: "12-Oct-2017"
结果是:“12 - 10月- 2017”
The date and time formats can be customized using the options argument.
可以使用选项参数定制日期和时间格式。
The Intl.DateTimeFormat
object is a constructor for objects that enable language sensitive date and time formatting.
Intl。DateTimeFormat对象是用于支持语言敏感日期和时间格式的对象的构造函数。
Syntax
语法
new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
Parameters
参数
locales
地区
Optional. A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page. The following Unicode extension keys are allowed:
可选的。一个带有BCP 47语言标记的字符串,或者是这样的字符串数组。对于locales参数的一般形式和解释,请参见Intl页面。允许下列Unicode扩展键:
nu
Numbering system. Possible values include: "arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt".
ca
Calendar. Possible values include: "buddhist", "chinese", "coptic", "ethioaa", "ethiopic", "gregory", "hebrew", "indian", "islamic", "islamicc", "iso8601", "japanese", "persian", "roc".
Options
选项
Optional. An object with some or all of the following properties:
可选的。一个具有以下属性的对象:
localeMatcher
localeMatcher
The locale matching algorithm to use. Possible values are "lookup"
and "best fit"
; the default is "best fit"
. For information about this option, see the Intl page.
区域匹配算法的使用。可能的值是“查找”和“最佳匹配”;默认值是“最佳匹配”。有关此选项的信息,请参见Intl页面。
timeZone
时区
The time zone to use. The only value implementations must recognize is "UTC"
; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai"
, "Asia/Kolkata"
, "America/New_York"
.
使用的时区。惟一的值实现必须识别为“UTC”;默认值是运行时的默认时区。实现还可以识别IANA时区数据库的时区名称,如“Asia/Shanghai”、“Asia/Kolkata”、“America/New_York”。
hour12
hour12
Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true
and false
; the default is locale dependent.
是否使用12小时的时间(相对于24小时的时间)。可能的值是真和假的;默认情况下是语言环境相关的。
formatMatcher
formatMatcher
The format matching algorithm to use. Possible values are "basic"
and "best fit"
; the default is "best fit"
. See the following paragraphs for information about the use of this property.
格式匹配算法的使用。可能的值是“基本的”和“最合适的”;默认值是“最佳匹配”。有关此属性的使用情况,请参阅以下各段。
The following properties describe the date-time components to use in formatted output and their desired representations. Implementations are required to support at least the following subsets:
下面的属性描述了在格式化输出中使用的日期时间组件及其所需的表示。实现需要至少支持以下子集:
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. Two algorithms are available for this negotiation and selected by the formatMatcher property: A fully specified "basic"
algorithm and an implementation dependent "best fit" algorithm.
实现可能支持其他子集,并且请求将与所有可用的子集合表示组合进行协商,以找到最佳匹配。两种算法可用于此协商,并由formatMatcher属性选择:完全指定的“基本”算法和依赖于“最佳匹配”算法的实现。
weekday
工作日
The representation of the weekday. Possible values are "narrow"
, "short"
, "long"
.
工作日的代表。可能的值是“窄”、“短”、“长”。
era
时代
The representation of the era. Possible values are "narrow"
, "short"
, "long"
.
时代的代表。可能的值是“窄”、“短”、“长”。
year
一年
The representation of the year. Possible values are "numeric"
, "2-digit"
.
年度代表。可能的值是“数字”,“2位”。
month
月
The representation of the month. Possible values are "numeric"
, "2-digit"
, "narrow"
, "short"
, "long"
.
这个月的代表。可能的值是“数字”、“2位”、“窄”、“短”、“长”。
day
一天
The representation of the day. Possible values are "numeric"
, "2-digit"
.
这一天的代表。可能的值是“数字”,“2位”。
hour
小时
The representation of the hour. Possible values are "numeric"
, "2-digit"
.
一小时的代表。可能的值是“数字”,“2位”。
minute
一分钟
The representation of the minute. Possible values are "numeric"
, "2-digit"
.
一分钟的代表。可能的值是“数字”,“2位”。
second
第二个
The representation of the second. Possible values are "numeric"
, "2-digit"
.
第二个的表示。可能的值是“数字”,“2位”。
timeZoneName
timeZoneName
The representation of the time zone name. Possible values are "short"
, "long"
. The default value for each date-time component property is undefined, but if all component properties are undefined, then the year, month and day are assumed to be "numeric"
.
时区名称的表示。可能的值是“短”、“长”。每个日期时间组件属性的默认值都是未定义的,但是如果所有组件属性都未定义,则假定年、月和日为“数值”。
检查在线
更多的细节
#22
8
new Date().toLocaleDateString()
// "3/21/2018"
More documentation at developer.mozilla.org
更多文档:developer.mozilla.org
#23
7
Sugar.js has excellent extensions to the Date object, including a Date.format method.
糖。js对Date对象有很好的扩展,包括一个日期。格式的方法。
Examples from the documentation:
从文档的例子:
Date.create().format('{Weekday} {Month} {dd}, {yyyy}');
Date.create().format('{12hr}:{mm}{tt}')
#24
7
OK, we have got something called Intl which is very useful for formatting a date in JavaScript:
好的,我们有一个叫做Intl的东西它对于格式化JavaScript的日期非常有用:
Your date as below:
你的日期如下:
var date = '10/8/2010';
And you change to Date by using new Date() like below:
你可以使用下面的新日期()来更改日期:
date = new Date(date);
And now you can format it any way you like using a list of locales like below:
现在你可以用下面的方式来格式化你喜欢的地方:
date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010"
date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010"
date = new Intl.DateTimeFormat('ar-EG').format(date); // Arabic date format: "٨/١٠/٢٠١٠"
If you exactly want the format you mentioned above, you can do:
如果你确实想要你上面提到的格式,你可以:
date = new Date(Date.UTC(2010, 7, 10, 0, 0, 0));
var options = {year: "numeric", month: "short", day: "numeric"};
date = new Intl.DateTimeFormat("en-AU", options).format(date).replace(/\s/g, '-');
And the result is going to be:
结果是:
"10-Aug-2010"
For more details about ECMAScript Internationalization API (Intl), visit here.
有关ECMAScript国际化API (Intl)的更多细节,请访问这里。
#25
4
Try this:
试试这个:
function init(){
var d = new Date();
var day = d.getDate();
var x = d.toDateString().substr(4, 3);
var year = d.getFullYear();
document.querySelector("#mydate").innerHTML = day + '-' + x + '-' + year;
}
window.onload = init;
<div id="mydate"></div>
#26
3
Here is a script that does exactly what you want
这里有一个脚本,它可以精确地执行您想要的操作。
https://github.com/UziTech/js-date-format
https://github.com/UziTech/js-date-format
var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));
#27
3
Inspired by JD Smith's marvellous regular expression solution, I suddenly had this head-splitting idea:
受到JD Smith绝妙的正则表达式解决方案的启发,我突然想到了一个令人头疼的想法:
var D = Date().toString().split(" ");
document.getElementById("demo").innerHTML = D[2] + "-" + D[1] + "-" + D[3];
#28
3
Hi check if this helps with your problem.
嗨,看看这对你的问题有没有帮助。
var d = new Date();
var options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
console.log(d.toLocaleDateString('en-ZA', options));
#29
2
I use the following. It is simple and works fine.
我使用下面的。它很简单,也很好用。
var dtFormat = require('dtformat');
var today = new Date();
dtFormat(today, "dddd, mmmm dS, yyyy, h:MM:ss TT");
Or this:
或:
var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)
#30
2
DateFormatter.formatDate(new Date(2010,7,10), 'DD-MMM-YYYY')
dateformat。formatDate(新日期(2010、7、10)、“DD-MMM-YYYY”)
=>10-Aug-2010
= > 10 - 8月- 2010
DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
dateformat。formatDate(新日期(),“YYYY-MM-DD HH:mm:ss”)
=>2017-11-22 19:52:37
= > 2017-11-22 19:52:37
DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A')
dateformat。格式日期(新日期(2005年,1,2,3,4,5),DD DDD DDDD, mmmmm, yyyyy, h hh, MMM, s ss, a ')
=>2 02 Wed Wednesday, 2 02 Feb February, 05 2005, 3 03 3 03, 4 04, 5 05, am AM
= >202星期三,2月2日,2005年2月5日,03 03 3 03,4 04,5 05,am。
var DateFormatter = {
monthNames: [
"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
],
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
formatDate: function (date, format) {
var self = this;
format = self.getProperDigits(format, /d+/gi, date.getDate());
format = self.getProperDigits(format, /M+/g, date.getMonth() + 1);
format = format.replace(/y+/gi, function (y) {
var len = y.length;
var year = date.getFullYear();
if (len == 2)
return (year + "").slice(-2);
else if (len == 4)
return year;
return y;
})
format = self.getProperDigits(format, /H+/g, date.getHours());
format = self.getProperDigits(format, /h+/g, self.getHours12(date.getHours()));
format = self.getProperDigits(format, /m+/g, date.getMinutes());
format = self.getProperDigits(format, /s+/gi, date.getSeconds());
format = format.replace(/a/ig, function (a) {
var amPm = self.getAmPm(date.getHours())
if (a === 'A')
return amPm.toUpperCase();
return amPm;
})
format = self.getFullOr3Letters(format, /d+/gi, self.dayNames, date.getDay())
format = self.getFullOr3Letters(format, /M+/g, self.monthNames, date.getMonth())
return format;
},
getProperDigits: function (format, regex, value) {
return format.replace(regex, function (m) {
var length = m.length;
if (length == 1)
return value;
else if (length == 2)
return ('0' + value).slice(-2);
return m;
})
},
getHours12: function (hours) {
// https://*.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method
return (hours + 24) % 12 || 12;
},
getAmPm: function (hours) {
// https://*.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format
return hours >= 12 ? 'pm' : 'am';
},
getFullOr3Letters: function (format, regex, nameArray, value) {
return format.replace(regex, function (s) {
var len = s.length;
if (len == 3)
return nameArray[value].substr(0, 3);
else if (len == 4)
return nameArray[value];
return s;
})
}
}
console.log(DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss'));
console.log(DateFormatter.formatDate(new Date(), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
console.log(DateFormatter.formatDate(new Date(2005, 1, 2, 3, 4, 5), 'D DD DDD DDDD, M MM MMM MMMM, YY YYYY, h hh H HH, m mm, s ss, a A'));
Format description was take Ionic Framework (does not support Z
,UTC Timezone Offset)
格式描述采用Ionic框架(不支持Z,UTC时区偏移)
Not thoroughly tested
没有彻底的测试