leo*_*ora 1945 javascript date date-format time-format
如何格式化要打印的JavaScript日期对象10-Aug-2010
?
小智 1762
toLocaleDateString()
该toLocaleDateString()
方法返回一个字符串,其中包含日期日期部分的语言敏感表示.locales和options参数允许应用程序指定应使用其格式约定的语言,并允许自定义函数的行为.
所有这些键都是可选的.您可以根据需要更改选项值的数量,这也将反映每个日期时间项的存在.
注意:如果您只想配置内容选项,但仍使用当前区域设置,则传递null
第一个参数将导致错误.请undefined
改用.
您可以使用更多语言选项.
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
Run Code Online (Sandbox Code Playgroud)
您也可以将此toLocaleString()
方法用于相同目的.唯一的区别是此功能提供了不传递任何选项的时间.
// Example
9/17/2016, 1:21:34 PM
Run Code Online (Sandbox Code Playgroud)
Mar*_*rko 1129
注意:下面有更好的答案.这个答案写于2010年,从那时起就有了更新更好的解决方案.OP应接受另一个答案.
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
Run Code Online (Sandbox Code Playgroud)
您可以编辑阵列monthNames
以使用Jan,Feb,Mar等.
Rob*_*itt 591
使用date.format库:
var dateFormat = require('dateformat');
var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
Run Code Online (Sandbox Code Playgroud)
收益:
Saturday, June 9th, 2007, 5:46:21 PM
Run Code Online (Sandbox Code Playgroud)
seb*_*n.i 468
如果你需要使用普通的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
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要用零填充:
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
Run Code Online (Sandbox Code Playgroud)
sim*_*imo 387
好吧,我想要的是将今天的日期转换为MySQL友好的日期字符串,如2012-06-23,并在我的一个查询中使用该字符串作为参数.我发现的简单解决方案是这样的:
var today = new Date().toISOString().slice(0, 10);
Run Code Online (Sandbox Code Playgroud)
请注意,上述解决方案未考虑您的时区偏移.
您可以考虑使用此功能:
function toJSONLocal (date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
Run Code Online (Sandbox Code Playgroud)
如果您在当天的开始/结束时执行此代码,这将为您提供正确的日期.
Adr*_*ire 197
对于固定格式,一个简单的功能可以完成工作.以下示例生成国际格式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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
注意:然而,扩展JavaScript标准库通常不是一个好主意(例如,通过将此函数添加到Date的原型).
更高级的功能可以基于格式参数生成可配置输出.
如果要编写格式化函数太长,那么就会有很多库.其他一些答案已经列举了它们.但是,越来越多的依赖关系也会与之相反.
由于ECMAScript的更新版本,Date
该类具有一些特定的格式化函数:
toDateString:依赖于实现,仅显示日期.
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.todatestring
Run Code Online (Sandbox Code Playgroud)new Date().toDateString(); // e.g. "Fri Nov 11 2016"
toISOString:显示ISO 8601日期和时间.
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.toisostring
Run Code Online (Sandbox Code Playgroud)new Date().toISOString(); // e.g. "2016-11-21T08:00:00.000Z"
toJSON:JSON的Stringifier.
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tojson
Run Code Online (Sandbox Code Playgroud)new Date().toJSON(); // e.g. "2016-11-21T08:00:00.000Z"
toLocaleDateString:依赖于实现,以区域设置格式的日期.
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaledatestring
Run Code Online (Sandbox Code Playgroud)new Date().toLocaleDateString(); // e.g. "21/11/2016"
toLocaleString:依赖于实现,以区域设置格式的日期和时间.
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocalestring
Run Code Online (Sandbox Code Playgroud)new Date().toLocaleString(); // e.g. "21/11/2016, 08:00:00 AM"
toLocaleTimeString:依赖于实现,是区域设置格式的时间.
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tolocaletimestring
Run Code Online (Sandbox Code Playgroud)new Date().toLocaleTimeString(); // e.g. "08:00:00 AM"
toString:Date的通用toString.
http://www.ecma-international.org/ecma-262/7.0/index.html#sec-date.prototype.tostring
Run Code Online (Sandbox Code Playgroud)new Date().toString(); // e.g. "Fri Nov 21 2016 08:00:00 GMT+0100 (W. Europe Standard Time)"
注意:可以从那些格式>生成自定义输出
Run Code Online (Sandbox Code Playgroud)new Date().toISOString().slice(0,10); //return YYYY-MM-DD
示例摘要:
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));
Run Code Online (Sandbox Code Playgroud)
Dmi*_*lov 172
如果您已经在项目中使用jQuery UI,则可以这样做:
var formatted = $.datepicker.formatDate("M d, yy", new Date("2014-07-08T09:02:21.377"));
// formatted will be 'Jul 8, 2014'
Run Code Online (Sandbox Code Playgroud)
此处提供了一些可供使用的日期选择器日期格式选项.
小智 128
我想你可以使用非标准的 Date方法toLocaleFormat(formatString)
formatString:strftime()
C中函数所需格式的格式字符串.
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
Run Code Online (Sandbox Code Playgroud)
参考文献:
Mit*_*ski 99
简单的JavaScript是小型onetimers的最佳选择.
另一方面,如果您需要更多日期,MomentJS是一个很好的解决方案.
例如:
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
Run Code Online (Sandbox Code Playgroud)
Joh*_*ers 94
在现代浏览器(*)中,您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
Run Code Online (Sandbox Code Playgroud)
如果今天执行输出(2016年1月24日):
'24-Jan-2016'
Run Code Online (Sandbox Code Playgroud)
(*) 根据MDN,"现代浏览器"意味着Chrome 24 +,Firefox 29 +,Internet Explorer 11,Edge 12 +,Opera 15+和Safari 夜间构建.
NiK*_*iKo 52
你应该看看date.js.它添加了许多方便的帮助程序来处理日期,例如,在您的情况下:
var date = Date.parse('2010-08-10');
console.log(date.toString('dd-MMM-yyyy'));
Run Code Online (Sandbox Code Playgroud)
入门:http://www.datejs.com/2007/11/27/getting-started-with-datejs/
use*_*584 35
@Sébastien - 替代所有浏览器支持
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
Run Code Online (Sandbox Code Playgroud)
文档:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
JD *_*ith 34
我可以在一行中使用没有库和没有Date方法获得您请求的格式,只是正则表达式:
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()')
Run Code Online (Sandbox Code Playgroud)
更新:正如@RobG所指出的,Date.prototype.toString()的输出是依赖于实现的.因此,如果您使用此解决方案,请谨慎使用并在必要时进行修改.在我的测试中,这在北美可靠地运行,主要浏览器(Chrome,Safari,Firefox和IE)都返回相同的字符串格式.
vde*_*nne 29
使用ECMAScript Edition 6(ES6/ES2015)字符串模板:
let d = new Date();
let formatted = `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
Run Code Online (Sandbox Code Playgroud)
如果您需要更改分隔符:
const delimiter = '/';
let formatted = [d.getFullYear(), d.getMonth() + 1, d.getDate()].join(delimiter);
Run Code Online (Sandbox Code Playgroud)
Ali*_*eza 26
好的,我们有一个名为Intl的东西,这对于在JavaScript中格式化日期非常有用:
您的日期如下:
var date = '10/8/2010';
Run Code Online (Sandbox Code Playgroud)
然后使用新的Date()更改为Date,如下所示:
date = new Date(date);
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用以下语言环境列表以任何方式格式化它:
date = new Intl.DateTimeFormat('en-AU').format(date); // Australian date format: "8/10/2010"
Run Code Online (Sandbox Code Playgroud)
date = new Intl.DateTimeFormat('en-US').format(date); // USA date format: "10/8/2010"
Run Code Online (Sandbox Code Playgroud)
date = new Intl.DateTimeFormat('ar-EG').format(date); // Arabic date format: "??/???/????"
Run Code Online (Sandbox Code Playgroud)
如果您确实需要上面提到的格式,您可以:
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, '-');
Run Code Online (Sandbox Code Playgroud)
结果将是:
"10-Aug-2010"
Run Code Online (Sandbox Code Playgroud)
有关ECMAScript Internationalization API(Intl)的更多详细信息,请访问此处.
lew*_*dev 24
打包解决方案: moment.js
如果你想使用一个解决方案来适应所有,我强烈建议使用moment.js,它也可以在许多语言环境/语言和大量其他功能中进行格式化.
安装:
npm install luxon
或yarn add luxon
(访问其他安装方法的链接)
例:
luxon.DateTime.fromISO('2010-08-10').toFormat('yyyy-LLL-dd');
产量:
10 - 8 - 2010
手动解决方案
使用与Moment.js,Class DateTimeFormatter(Java)和Class SimpleDateFormat(Java)类似的格式,我实现了一个全面的解决方案formatDate(date, patternStr)
,其中代码易于阅读和修改.您可以显示日期,时间,上午/下午等.有关更多示例,请参阅代码.
例:
formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss:S')
(formatDate
在下面的代码片段中实现)
产量:
2018年10月12日星期五18:11:23:445
点击"运行代码段"即可试用该代码.
日期和时间模式
yy
= 2位数年份; yyyy
=全年
M
=数字月; MM
= 2位数月份; MMM
=短月名; MMMM
=完整的月份名称
EEEE
=完整的工作日名称; EEE
=工作日的简短名称
d
=数字日; dd
= 2位数日
h
=上午/下午; hh
=上午2点/下午; H
=小时; HH
= 2位数小时
m
=分钟; mm
= 2位数分钟; aaa
=上午/下午
s
=秒; ss
= 2位数秒
S
=毫秒
var monthNames = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
];
var dayOfWeekNames = [
"Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday"
];
function formatDate(date, patternStr){
if (!patternStr) {
patternStr = 'M/d/yyyy';
}
var day = date.getDate(),
month = date.getMonth(),
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
second = date.getSeconds(),
miliseconds = date.getMilliseconds(),
h = hour % 12,
hh = twoDigitPad(h),
HH = twoDigitPad(hour),
mm = twoDigitPad(minute),
ss = twoDigitPad(second),
aaa = hour < 12 ? 'AM' : 'PM',
EEEE = dayOfWeekNames[date.getDay()],
EEE = EEEE.substr(0, 3),
dd = twoDigitPad(day),
M = month + 1,
MM = twoDigitPad(M),
MMMM = monthNames[month],
MMM = MMMM.substr(0, 3),
yyyy = year + "",
yy = yyyy.substr(2, 2)
;
// checks to see if month name will be used
patternStr = patternStr
.replace('hh', hh).replace('h', h)
.replace('HH', HH).replace('H', hour)
.replace('mm', mm).replace('m', minute)
.replace('ss', ss).replace('s', second)
.replace('S', miliseconds)
.replace('dd', dd).replace('d', day)
.replace('EEEE', EEEE).replace('EEE', EEE)
.replace('yyyy', yyyy)
.replace('yy', yy)
.replace('aaa', aaa);
if (patternStr.indexOf('MMM') > -1) {
patternStr = patternStr
.replace('MMMM', MMMM)
.replace('MMM', MMM);
}
else {
patternStr = patternStr
.replace('MM', MM)
.replace('M', M);
}
return patternStr;
}
function twoDigitPad(num) {
return num < 10 ? "0" + num : num;
}
console.log(formatDate(new Date()));
console.log(formatDate(new Date(), 'dd-MMM-yyyy')); //OP's request
console.log(formatDate(new Date(), 'EEEE, MMMM d, yyyy HH:mm:ss.S aaa'));
console.log(formatDate(new Date(), 'EEE, MMM d, yyyy HH:mm'));
console.log(formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss.S'));
console.log(formatDate(new Date(), 'M/dd/yyyy h:mmaaa'));
Run Code Online (Sandbox Code Playgroud)
jmi*_*lia 18
这是我刚刚编写的一些代码,用于处理我正在处理的项目的日期格式.它模仿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
*
************************************/
Run Code Online (Sandbox Code Playgroud)
tod*_*dmo 16
它可以轻松增强以支持任何所需的格式字符串。当像这样的通用解决方案很容易创建,并且日期格式在应用程序中经常出现时,我不建议在整个应用程序中硬编码日期格式代码。它更难阅读并且隐藏你的意图。格式字符串清楚地表明您的意图。
interface Date {
format(formatString: string): string;
}
Date.prototype.format = function (formatString: string): string {
return Object.entries({
YYYY: this.getFullYear(),
YY: this.getFullYear().toString().substring(2),
yyyy: this.getFullYear(),
yy: this.getFullYear().toString().substring(2),
MMMM: this.toLocaleString('default', { month: 'long' }),
MMM: this.toLocaleString('default', { month: 'short' }),
MM: (this.getMonth() + 1).toString().padStart(2, '0'),
M: this.getMonth() + 1,
DDDD: this.toLocaleDateString('default', { weekday: 'long' }),
DDD: this.toLocaleDateString('default', { weekday: 'short' }),
DD: this.getDate().toString().padStart(2, '0'),
D: this.getDate(),
dddd: this.toLocaleDateString('default', { weekday: 'long' }),
ddd: this.toLocaleDateString('default', { weekday: 'short' }),
dd: this.getDate().toString().padStart(2, '0'),
d: this.getDate(),
HH: this.getHours().toString().padStart(2, '0'), // military
H: this.getHours().toString(), // military
hh: (this.getHours() % 12).toString().padStart(2, '0'),
h: (this.getHours() % 12).toString(),
mm: this.getMinutes().toString().padStart(2, '0'),
m: this.getMinutes(),
SS: this.getSeconds().toString().padStart(2, '0'),
S: this.getSeconds(),
ss: this.getSeconds().toString().padStart(2, '0'),
s: this.getSeconds(),
TTT: this.getMilliseconds().toString().padStart(3, '0'),
ttt: this.getMilliseconds().toString().padStart(3, '0'),
AMPM: this.getHours() < 13 ? 'AM' : 'PM',
ampm: this.getHours() < 13 ? 'am' : 'pm',
}).reduce((acc, entry) => {
return acc.replace(entry[0], entry[1].toString())
}, formatString)
}
Run Code Online (Sandbox Code Playgroud)
function unitTest() {
var d: Date = new Date()
console.log(d.format('MM/dd/yyyy hh:mm:ss')) // 12/14/2022 03:38:31
console.log(d.format('yyyy-MM-dd HH:mm:ss')) // 2022-12-14 15:38:31
}
unitTest()
Run Code Online (Sandbox Code Playgroud)
一样的。只需删除接口以及冒号后面的类型名称及其关联的冒号即可。
interface Date {
format(formatString: string): string;
}
Date.prototype.format = function (formatString: string): string {
return Object.entries({
YYYY: this.getFullYear(),
YY: this.getFullYear().toString().substring(2),
yyyy: this.getFullYear(),
yy: this.getFullYear().toString().substring(2),
MMMM: this.toLocaleString('default', { month: 'long' }),
MMM: this.toLocaleString('default', { month: 'short' }),
MM: (this.getMonth() + 1).toString().padStart(2, '0'),
M: this.getMonth() + 1,
DDDD: this.toLocaleDateString('default', { weekday: 'long' }),
DDD: this.toLocaleDateString('default', { weekday: 'short' }),
DD: this.getDate().toString().padStart(2, '0'),
D: this.getDate(),
dddd: this.toLocaleDateString('default', { weekday: 'long' }),
ddd: this.toLocaleDateString('default', { weekday: 'short' }),
dd: this.getDate().toString().padStart(2, '0'),
d: this.getDate(),
HH: this.getHours().toString().padStart(2, '0'), // military
H: this.getHours().toString(), // military
hh: (this.getHours() % 12).toString().padStart(2, '0'),
h: (this.getHours() % 12).toString(),
mm: this.getMinutes().toString().padStart(2, '0'),
m: this.getMinutes(),
SS: this.getSeconds().toString().padStart(2, '0'),
S: this.getSeconds(),
ss: this.getSeconds().toString().padStart(2, '0'),
s: this.getSeconds(),
TTT: this.getMilliseconds().toString().padStart(3, '0'),
ttt: this.getMilliseconds().toString().padStart(3, '0'),
AMPM: this.getHours() < 13 ? 'AM' : 'PM',
ampm: this.getHours() < 13 ? 'am' : 'pm',
}).reduce((acc, entry) => {
return acc.replace(entry[0], entry[1].toString())
}, formatString)
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*DLV 15
不使用任何外部库的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)
Run Code Online (Sandbox Code Playgroud)
web*_*bzy 15
如果您在代码中使用jQuery UI,则会调用一个内置函数formatDate()
.我这样使用它来格式化今天的日期:
var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);
Run Code Online (Sandbox Code Playgroud)
您可以在jQuery UI文档中看到 许多其他格式化日期示例.
Vij*_*iya 15
我们有很多解决方案,但我认为其中最好的是Moment.js.所以我个人建议使用Moment.js进行日期和时间操作.
console.log(moment().format('DD-MMM-YYYY'));
Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
Run Code Online (Sandbox Code Playgroud)
Ima*_*our 15
在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,'-'));
Run Code Online (Sandbox Code Playgroud)
结果是: "12-Oct-2017"
可以使用options参数自定义日期和时间格式.
该Intl.DateTimeFormat
对象是对象的构造函数,用于启用语言敏感的日期和时间格式.
句法
new Intl.DateTimeFormat([locales[, options]])
Intl.DateTimeFormat.call(this[, locales[, options]])
Run Code Online (Sandbox Code Playgroud)
参数
语言环境
可选的.带有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".
Run Code Online (Sandbox Code Playgroud)
选项
可选的.具有以下部分或全部属性的对象:
localeMatcher
要使用的区域设置匹配算法.可能的值是"lookup"
和"best fit"
; 默认是"best fit"
.有关此选项的信息,请参阅Intl页面.
时区
要使用的时区.实现必须识别的唯一值是"UTC"
; 默认值是运行时的默认时区.实现也可以识别IANA时区数据库的时区名称,例如"Asia/Shanghai"
,"Asia/Kolkata"
,"America/New_York"
.
hour12
是否使用12小时时间(而不是24小时时间).可能的值是true
和false
; 默认值取决于语言环境.
formatMatcher
要使用的格式匹配算法.可能的值是"basic"
和"best fit"
; 默认是"best fit"
.有关使用此属性的信息,请参阅以下段落.
以下属性描述了在格式化输出中使用的日期时间组件及其所需的表示形式.需要实现至少支持以下子集:
weekday, year, month, day, hour, minute, second
weekday, year, month, day
year, month, day
year, month
month, day
hour, minute, second
hour, minute
Run Code Online (Sandbox Code Playgroud)
实现可以支持其他子集,并且将针对所有可用的子集表示组合协商请求以找到最佳匹配.有两种算法可用于此协商,并由formatMatcher属性选择:完全指定的"basic"
算法和依赖于实现的"最佳拟合"算法.
平日
工作日的代表.可能的值是"narrow"
,"short"
,"long"
.
时代
时代的代表.可能的值是"narrow"
,"short"
,"long"
.
年
年度代表.可能的值是"numeric"
,"2-digit"
.
月
本月的代表.可能的值是"numeric"
,"2-digit"
,"narrow"
,"short"
,"long"
.
天
当天的代表.可能的值是"numeric"
,"2-digit"
.
小时
小时的表示.可能的值是"numeric"
,"2-digit"
.
分钟
分钟的表示.可能的值是"numeric"
,"2-digit"
.
第二
第二个的表示.可能的值是"numeric"
,"2-digit"
.
TIMEZONENAME
时区名称的表示形式.可能的值是"short"
,"long"
.每个日期时间组件属性的默认值是未定义的,但如果未定义所有组件属性,则假定年,月和日"numeric"
.
Mr *_*uga 14
嗨检查这是否有助于解决您的问题.
var d = new Date();
var options = {
day: 'numeric',
month: 'long',
year: 'numeric'
};
console.log(d.toLocaleDateString('en-ZA', options));
Run Code Online (Sandbox Code Playgroud)
Mel*_*hia 14
你应该看看DayJs 它是对 momentJs 的重制,但面向模块化架构的更轻。
具有相同现代 API 的 Moment.js 的快速 2kB 替代品
Day.js 是一个极简的 JavaScript 库,它使用与 Moment.js 兼容的 API 为现代浏览器解析、验证、操作和显示日期和时间。如果您使用 Moment.js,您就已经知道如何使用 Day.js。
var date = Date.now();
const formatedDate = dayjs(date).format("YYYY-MM-DD")
console.log(formatedDate);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js" crossorigin="anonymous"></script>
Run Code Online (Sandbox Code Playgroud)
Ami*_*pta 13
这就是我为我的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;
}
Run Code Online (Sandbox Code Playgroud)
ppi*_*com 13
的Date
构造(和Date.parse()
)仅构建日期时接受一个格式作为一个参数,那就是ISO 8601:
// new Date('YYYY-MM-DDTHH:mm:ss.sssZ')
const date = new Date('2017-08-15')
Run Code Online (Sandbox Code Playgroud)
但是由于浏览器的差异和不一致,强烈建议不要从字符串解析 a(MDN 建议不要使用日期字符串创建日期)。
推荐的替代方法是直接从数字数据构建您的 Date 实例,如下所示:
new Date(2017, 7, 15) // month is zero-indexed
Run Code Online (Sandbox Code Playgroud)
那就是解析。现在,要将您的日期格式化为您想要的字符串,您有几个 Date 对象本机的选项(尽管我相信没有一个选项符合您需要的格式):
date.toString() // 'Wed Jan 23 2019 17:23:42 GMT+0800 (Singapore Standard Time)'
date.toDateString() // 'Wed Jan 23 2019'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toLocaleString() // '23/01/2019, 17:23:42'
date.toGMTString() // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toUTCString() // 'Wed, 23 Jan 2019 09:23:42 GMT'
date.toISOString() // '2019-01-23T09:23:42.079Z'
Run Code Online (Sandbox Code Playgroud)
对于其他格式选项,恐怕您将不得不求助于诸如moment.js、day.js之类的库。
Dav*_*ave 10
受到JD Smith奇妙的正则表达式解决方案的启发,我突然有了这个令人头疼的想法:
var D = Date().toString().split(" ");
console.log(D[2] + "-" + D[1] + "-" + D[3]);
Run Code Online (Sandbox Code Playgroud)
cat*_*ith 10
简单的格式化程序:
function fmt(date, format = 'YYYY-MM-DDThh:mm:ss') {
const pad2 = (n) => n.toString().padStart(2, '0');
const map = {
YYYY: date.getFullYear(),
MM: pad2(date.getMonth() + 1),
DD: pad2(date.getDate()),
hh: pad2(date.getHours()),
mm: pad2(date.getMinutes()),
ss: pad2(date.getSeconds()),
};
return Object.entries(map).reduce((prev, entry) => prev.replace(...entry), format);
}
// Usage
console.log(
fmt(new Date(), 'YYYY-MM-DDThh:mm:ss') // '2023-03-04T10:30:24'
);
console.log(
fmt(new Date(), 'MM/DD/YYYY, hh:mm:ss') // '03/04/2023, 10:30:24'
);
Run Code Online (Sandbox Code Playgroud)
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
Run Code Online (Sandbox Code Playgroud)
为了格式化日期例如10-Aug-2010
,你可能想使用.toDateString()
和ES6阵列解构。
const formattedDate = new Date().toDateString()
// The above yields e.g. 'Mon Jan 06 2020'
const [, month, day, year] = formattedDate.split(' ')
const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')
Run Code Online (Sandbox Code Playgroud)
Sugar.js具有对Date对象的出色扩展,包括Date.format方法.
文档中的示例:
Date.create().format('{Weekday} {Month} {dd}, {yyyy}');
Date.create().format('{12hr}:{mm}{tt}')
Run Code Online (Sandbox Code Playgroud)
JavaScriptIntl.DateTimeFormat
方法提供了一种格式化日期的便捷方法。
以下是构建所需格式的方法:
const date = new Date("2010-08-10");
let d=new Intl.DateTimeFormat('en-GB',{year:"numeric", month:"short",day:"2-digit"}).format(date).split(" ").join("-");
console.log(d);
Run Code Online (Sandbox Code Playgroud)
小智 8
你可以简单地这样做:
let date = new Date().toLocaleDateString('en-us', {day: 'numeric'})
let month = new Date().toLocaleDateString('en-us', {month: 'long'})
let year = new Date().toLocaleDateString('en-us', {year: 'numeric'})
const FormattedDate = `${date}-${month}-${year}`
console.log(FormattedDate) // 26-March-2022
Run Code Online (Sandbox Code Playgroud)
任何人都在寻找一个非常简单的ES6解决方案来复制,粘贴和采用:
const dateToString = d => `${d.getFullYear()}-${('00' + (d.getMonth() + 1)).slice(-2)}-${('00' + d.getDate()).slice(-2)}`
// how to use:
const myDate = new Date(Date.parse('04 Dec 1995 00:12:00 GMT'))
console.log(dateToString(myDate)) // 1995-12-04
Run Code Online (Sandbox Code Playgroud)
尝试这个:
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;
Run Code Online (Sandbox Code Playgroud)
<div id="mydate"></div>
Run Code Online (Sandbox Code Playgroud)
要获取“ 2010年8月10日”,请尝试:
var date = new Date('2010-08-10 00:00:00');
date = date.toLocaleDateString(undefined, {day:'2-digit'}) + '-' + date.toLocaleDateString(undefined, {month:'short'}) + '-' + date.toLocaleDateString(undefined, {year:'numeric'})
Run Code Online (Sandbox Code Playgroud)
有关浏览器的支持,请参见toLocaleDateString。
DateFormatter.formatDate(new Date(2010,7,10), 'DD-MMM-YYYY')
=>10-Aug-2010
DateFormatter.formatDate(new Date(), 'YYYY-MM-DD HH:mm:ss')
=>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')
=>2 02 Wed Wednesday, 2 02 Feb February, 05 2005, 3 03 3 03, 4 04, 5 05, am 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://stackoverflow.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://stackoverflow.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'));
Run Code Online (Sandbox Code Playgroud)
格式描述取自Ionic Framework(它不支持Z
, UTC 时区偏移)
没有经过彻底测试
截至2019年,您似乎可以获取toLocaleDateString仅返回某些部分,然后可以根据需要加入它们:
var date = new Date();
console.log(date.toLocaleDateString("en-US", { day: 'numeric' })
+ "-"+ date.toLocaleDateString("en-US", { month: 'short' })
+ "-" + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> 16-Nov-2019
console.log(date.toLocaleDateString("en-US", { month: 'long' })
+ " " + date.toLocaleDateString("en-US", { day: 'numeric' })
+ ", " + date.toLocaleDateString("en-US", { year: 'numeric' }) );
> November 16, 2019
Run Code Online (Sandbox Code Playgroud)
在这个答案中,我发展了JD Smith 的想法。我能够缩短 JD Smith regexp
let format= d=> d.toString().replace(/\w+ (\w+) (\d+) (\d+).*/,'$2-$1-$3');
console.log( format(Date()) );
Run Code Online (Sandbox Code Playgroud)
Dave也基于 JD Smith 的想法,但他避免使用正则表达式并提供非常好的解决方案 - 我缩短了他的解决方案(通过更改拆分参数)并将其在包装器中不透明
let format= (d,a=d.toString().split` `)=> a[2]+"-"+a[1]+"-"+a[3];
console.log( format(Date()) );
Run Code Online (Sandbox Code Playgroud)
在 IE 11、FF 和 Chrome 中工作相同(Chrome 80.x 在选择 en-UK 时显示 12 小时格式)。
const d = new Date('2010/08/05 23:45') // 26.3.2020
const dtfUK = new Intl.DateTimeFormat('UK', { year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
const dtfUS = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit',minute: '2-digit', second: '2-digit' }); //
console.log(dtfUS.format(d)); // 08/05/2010 11:45:00 PM
console.log(dtfUK.format(d)); // 05.08.2010 23:45:00
/* node.js:
08/05/2010, 11:45:00 PM
2010-08-05 23:45:00
*/
Run Code Online (Sandbox Code Playgroud)
更一般的东西呢?
var d = new Date('2010-08-10T10:34:56.789Z');
var str = d.toDateString() + // Tue Aug 10 2010
' ' + d.toTimeString().split(' ')[0] + // 12:34:56, GMT+0x00 (GMT+0x:00)
' ' + (d.getMonth() + 101) + // 108
' ' + d.getMilliseconds(); // 789
console.log(str); // Tue Aug 10 2010 12:34:56 108 789
console.log(// $1 Tue $2 Aug $3 11 $4 2020 $5 12 $6 34 $7 56 $8 108 $9 789
str.replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, '$3-$2-$4 $5:$6.$9 ($1)')
); // 10-Aug-2010 12:34.789 (Tue)
/*
$1: Tue Week Day string
$2: Aug Month short text
$3: 11 Day
$4: 2010 Year
$5: 12 Hour
$6: 34 Minute
$7: 56 Seconds
$8: 08 Month
$9: 789 Milliseconds
*/
Run Code Online (Sandbox Code Playgroud)
或者例如 1-line IIFE "library" ;-)
console.log(
(function (frm, d) { return [d.toDateString(), d.toTimeString().split(' ')[0], (d.getMonth() + 101), d.getMilliseconds()].join(' ').replace(/(\S{3}) (\S{3}) (\d{1,2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) 1(\d{2}) (\d{1,3})/, frm); })
('$4/$8/$3 $5:$6 ($1)', new Date())
);
Run Code Online (Sandbox Code Playgroud)
如果您不需要它们,您可以删除无用的部分和/或更改索引。
示例:“2023-04-25 00:01:23”
var currentdate = new Date();
var startedAt = currentdate.getFullYear() + "-" +
(currentdate.getMonth() + 1).toString().padStart(2, '0') + "-" +
currentdate.getDate().toString().padStart(2, '0') + " " +
currentdate.getHours().toString().padStart(2, '0') + ":" +
currentdate.getMinutes().toString().padStart(2, '0') + ":" +
currentdate.getSeconds().toString().padStart(2, '0');
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3316585 次 |
最近记录: |