如何将Date对象格式化为字符串?


当前回答

这是一个完全符合您要求的脚本

https://github.com/UziTech/js-date-format

var d = new Date("2010-8-10");
document.write(d.format("DD-MMM-YYYY"));

其他回答

如果在代码中使用jQueryUI,则有一个内置函数,名为formatDate()。我用这种方式设置今天的日期:

var testdate = Date();
testdate = $.datepicker.formatDate( "d-M-yy",new Date(testdate));
alert(testdate);

在jQueryUI文档中可以看到许多其他格式化日期的示例。

好的,我们有一个叫做Intl的东西,这对在JavaScript中格式化日期非常有用:

您的日期如下:

var date = '10/8/2010';

然后使用如下所示的新Date()更改为Date:

date = new Date(date);

现在,您可以使用以下区域设置列表以任何方式对其进行格式化:

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: "٨‏/١٠‏/٢٠١٠"

如果您确实想要上面提到的格式,可以执行以下操作:

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, '-');

结果将是:

"10-Aug-2010"

有关详细信息,请参阅Intl API和Intl.DateTimeFormat文档。

已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js2010年8月10日为:

var str = clock.month
str.charAt(0).toUpperCase() + str.slice(1,3); //gets you "Aug"
console.log(clock.day + '-' + str + '-' + clock.year); //gets you 10-Aug-2010



如果你想要一个简短的、人类可读的函数,这个函数很容易调整以适合你。

timeStamp参数是1970年的毫秒-它由new Date().getTime()和许多其他设备返回。。。

好吧,我改变主意了。我包含了一个额外的零填充函数。诅咒!

 function zeroPad(aNumber) {
     return ("0"+aNumber).slice(-2);
 }
 function humanTime(timeStamp) {
    var M = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var D = new Date(timeStamp); // 23 Aug 2016 16:45:59 <-- Desired format.
    return D.getDate() + " " + M[D.getMonth()] + " " + D.getFullYear() + " " + D.getHours() + ":" + zeroPad(d.getMinutes()) + ":" + zeroPad(D.getSeconds());
 }

对于自定义分隔日期格式,必须拉出日期(或时间)DateTimeFormat对象(它是ECMAScript国际化API),然后手动创建字符串使用所需的分隔符。

为此,可以使用DateTimeFormat#formatToParts。你可以销毁数组,但这并不理想,因为数组输出取决于区域设置:

{//示例1设f=新Intl.DateTimeFormat('en');让a=f.formatToParts();控制台日志(a);}{//示例2设f=新Intl.DateTimeFormat('hi');让a=f.formatToParts();控制台日志(a);}

最好将格式数组映射到结果字符串:

函数连接(t,a,s){函数格式(m){设f=新Intl.DateTimeFormat('en',m);返回f.format(t);}返回.map(格式).join(s);}让a=〔{日:‘数字’},{月:‘短’}、{年:‘数字”}〕;let s=join(新日期,a,'-');console.log;

还可以使用DateTimeFormat#格式,但请注意,使用此方法时,截至3月2020年,当涉及到分钟和秒的前导零(该方法避免了此错误以上)。

设d=新日期(2010,7,5);let ye=新Intl.DateTimeFormat('en',{year:'numeric'}).format(d);let mo=新Intl.DateTimeFormat('en',{month:'short'}).format(d);let da=新Intl.DateTimeFormat('en',{day:'2-位'}).format(d);console.log(`${da}--${mo}-${ye}');

在处理日期和时间时,通常值得使用库(例如,luxon、date fns、moment.js不建议用于新项目),因为该领域有许多隐藏的复杂性。

注意,上述解决方案中使用的ECMAScript国际化APIIE10不支持(2月全球浏览器市场份额为0.03%)2020).