如何将Date对象格式化为字符串?
当前回答
Use:
thisDate = new Date(parseInt(jsonDateString.replace('/Date(', '')));
formattedDate = (thisDate.getMonth() + 1) + "/" + (thisDate.getDate()+1) + "/" + thisDate.getFullYear();
这采用JSON日期“/date(1429573751663)/”,并生成格式化字符串:
"4/21/2015"
其他回答
使用此步骤
const MONTHS=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','9','Oct','Nov','Dec']const date=新日期()const dateString=`${date.getDate()}-${MONTHS[date.getMonth()]}--${date.getFullYear()}`console.log(dateString)
自定义格式设置函数:
对于固定格式,一个简单的函数即可完成任务。以下示例生成国际格式YYYY-MM-DD:
函数dateToYMD(日期){var d=date.getDate();var m=date.getMonth()+1//从0到11的月份var y=date.getFullYear();返回“”+y+“-”+(m<=9?“0”+m:m)+”-“+(d<=9!“0”+d:d);}console.log(dateToYMD(新日期(2017,10,5));//11月5日
OP格式可以如下生成:
函数dateToYMD(日期){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();返回“”+(d<=9?“0”+d:d)+“-”+“+m+”-“+y;}console.log(dateToYMD(新日期(2017,10,5));//11月5日
注意:然而,扩展JavaScript标准库通常不是一个好主意(例如,通过将此函数添加到Date的原型中)。
更高级的功能可以基于格式参数生成可配置的输出。
如果编写一个格式化函数太长,那么周围有很多库可以执行它。其他一些答案已经列举了它们。但日益增加的依赖性也有反作用。
标准ECMAScript格式化函数:
自从ECMAScript的最新版本以来,Date类具有一些特定的格式化函数:
toDateString:依赖于实现,仅显示日期。https://262.ecma-international.org/#sec-日期.协议类型.日期new Date().toDateString();//例如“2016年11月11日星期五”
toISOString:显示ISO 8601日期和时间。https://262.ecma-international.org/#sec-日期.协议类型.toisostringnew Date().toISOString();//例如“2016-11-21T08:00:00.000Z”
toJSON:JSON的Stringer。https://262.ecma-international.org/#sec-日期.原型.项目new Date().toJSON();//例如“2016-11-21T08:00:00.000Z”
toLocaleDateString:依赖于实现,区域设置格式的日期。https://262.ecma-international.org/#sec-日期.协议类型.颜色日期字符串new Date().toLocaleDateString();//例如“2016年11月21日”
toLocaleString:依赖于实现,是区域设置格式的日期和时间。https://262.ecma-international.org/#sec-日期.协议类型.颜色字符串new Date().toLocaleString();//例如“2016年11月21日上午08:00:00”
toLocaleTimeString:依赖于实现,以区域设置格式表示时间。https://262.ecma-international.org/#sec-日期.协议类型.颜色时间字符串new Date().toLocaleTimeString();//例如“08:00:00 AM”
toString:日期的通用toString。https://262.ecma-international.org/#sec-日期.协议类型.测试new Date().toString();//例如“2016年11月21日星期五08:00:00 GMT+0100(西欧标准时间)”
注意:可以使用这些格式生成自定义输出>
new Date().toISOString().slice(0,10)//返回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));
指定标准函数的区域设置:
上面列出的一些标准函数取决于语言环境:
到LocaleDateString()到LocaleTimeString()到LocalString()
这是因为不同的文化使用不同的格式,并以不同的方式表达他们的日期或时间。默认情况下,该函数将返回在其运行的设备上配置的格式,但这可以通过设置参数(ECMA-402)来指定。
toLocaleDateString([locales[, options]])
toLocaleTimeString([locales[, options]])
toLocaleString([locales[, options]])
//e.g. toLocaleDateString('ko-KR');
选项第二个参数允许在所选区域设置中配置更具体的格式。例如,月份可以显示为全文或删节。
toLocaleString('en-GB', { month: 'short' })
toLocaleString('en-GB', { month: 'long' })
示例片段:console.log(“1)”+new Date().toLocaleString('en-US'));console.log(“2)”+new Date().toLocaleString('ko-KR'));console.log(“3)”+新日期().toLocaleString('de-CH'));console.log(“4)”+new Date().toLocaleString('en-GB',{hour12:false}));console.log(“5)”+new Date().toLocaleString('en-GB',{hour12:true}));
关于区域设置的一些良好做法:
大多数人不喜欢他们的日期以外国人的格式显示,因此,尽可能保持默认的语言环境(而不是到处设置“en-US”)。实现从UTC到UTC的转换可能具有挑战性(考虑到DST、时区不是1小时的倍数等)。尽可能使用经过良好测试的库。不要假设语言环境与一个国家相关:几个国家都有很多语言环境(加拿大、印度等)避免通过非标准方式检测区域设置。在这里,您可以了解到多个陷阱:检测键盘布局、按地理位置检测区域设置等。。
在现代浏览器(*)中,您可以这样做:
var today = new Date().toLocaleDateString('en-GB', {
day : 'numeric',
month : 'short',
year : 'numeric'
}).split(' ').join('-');
如果今天(1月24日)执行输出ᵗʰ, 2016):
'24-Jan-2016'
(*)根据MDN,“现代浏览器”是指Chrome 24+、Firefox 29+、Internet Explorer 11、Edge 12+、Opera 15+和Safari夜间版本。
这是我实现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;
}
以下代码将允许您将日期格式设置为DD-MM-YYYY(2017年12月27日)或DD-MM-YYYY(2017年10月26日):
/** Pad number to fit into nearest power of 10 */
function padNumber(number, prependChar, count) {
var out = '' + number; var i;
if (number < Math.pow(10, count))
while (out.length < ('' + Math.pow(10, count)).length) out = prependChar + out;
return out;
}
/* Format the date to 'DD-MM-YYYY' or 'DD MMM YYYY' */
function dateToDMY(date, useNumbersOnly) {
var months = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct',
'Nov', 'Dec'
];
return '' + padNumber(date.getDate(), '0', 1) +
(useNumbersOnly? '-' + padNumber(date.getMonth() + 1, '0', 1) + '-' : ' ' + months[date.getMonth()] + ' ')
+ date.getFullYear();
}
更改date.getFullYear()和padNumber(date.getDate(),“0”,1)的顺序,以生成dateToYMD()函数。
有关详细信息,请参见repl.it示例。
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?