如何将Date对象格式化为字符串?
当前回答
以下代码将允许您将日期格式设置为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示例。
其他回答
这可能有助于解决问题:
var d=新日期();var选项={day:'数字',月份:'long',年份:'数字'};console.log(d.toLocaleDateString('en-ZA',选项));
你应该看看DayJs。它是momentJs的翻版,但模块化架构更轻。
快速2kB替代Moment.js,具有相同的现代API
Day.js是一个极简的JavaScript库,它使用Moment.js兼容的API为现代浏览器解析、验证、操作和显示日期和时间。如果您使用Moment.js,您已经知道如何使用Day.js。
var date=date.now();const formatedDate=dayjs(日期).format(“YYYY-MM-DD”)console.log(formatedDate);<script src=“https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js“crossoorigin=”匿名“></script>
将日期格式化为不同格式
let objectDate=新日期();let day=objectDate.getDate();console.log(天);//12let currentmo=objectDate.getMonth();月=当前月+1;console.log(月+1);//1.let year=objectDate.getFullYear();console.log(年);//2023//现在您可以相应地进行设置//日/月/年console.log(日+‘/‘+月+‘/’+年);//年/月/日console.log(月+'/'+day+'/'+年);
尝试此代码-https://bbbootstrap.com/code/format-date-javascript-49065802
嗯,我想要的是将今天的日期转换为MySQL友好的日期字符串,如2012-06-23,并在我的一个查询中使用该字符串作为参数。我找到的简单解决方案是:
var today = new Date().toISOString().slice(0, 10);
请记住,上述解决方案没有考虑您的时区偏移。
您可以考虑改用此函数:
function toJSONLocal (date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
这将为您提供正确的日期,以防您在一天的开始/结束时执行此代码。
var date=新日期();函数到本地(日期){var local=新日期(日期);local.setMinutes(date.getMinutes()-date.getTimezoneOffset());return local.toJSON();}函数到JSONLocal(日期){var local=新日期(日期);local.setMinutes(date.getMinutes()-date.getTimezoneOffset());return local.toJSON().slice(0,10);}//查看您的devtools控制台console.log(date.toJSON());console.log(date.toISOString());console.log(toLocal(日期));console.log(toJSONLocal(日期));
日期.toISOString日期.toJSON字符串切片外部示例
注意(2022-10):toLocaleFormat已被弃用一段时间,并从Firefox版本58中删除。请参见LocaleFormat
我想你可以使用非标准的Date方法来LocaleFormat(formatString)
formatString:与C中strftime()函数期望的格式相同的格式字符串。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
参考文献:
到区域设置格式斯特夫蒂姆