简体   繁体   English

以指定格式输出日期字符串

[英]Output datestring in specified format

I have seen a lot of posts about parsing strings into dates, but not such definitive answers about the other direction, dates into strings of the desired format. 我见过很多有关将字符串解析为日期的文章,但没有关于将字符串解析为所需格式的其他明确答案。

I have a Javascript Date (which I made from Date(unixtimestamp) ) and I want a string that looks like 'YYYY-MM-DD HH:MM' . 我有一个Javascript Date (由Date(unixtimestamp)制成),我想要一个看起来像'YYYY-MM-DD HH:MM'的字符串。 Sure, I could get year, month, day, hour, and min and manually make the string with the dashes and colon, but that's multiple lines where I wonder if a single line of someone else's code will do. 当然,我可以获取年,月,日,小时和分钟,并用破折号和冒号手动创建字符串,但这是多行代码,我想知道其他人的代码是否可以完成。

Any thoughts? 有什么想法吗?

Date.toISOString returns almost what you want. Date.toISOString返回几乎所需的内容。

var d= new Date();
var s= d.toISOString();

/* returned value: (String) 2014-07-28T18:26:46.550Z */ / *返回值:(String)2014-07-28T18:26:46.550Z * /

You can tinker with the return in the same line of code- 您可以在同一行代码中修改收益-

var d= new Date();
var s= d.toISOString().replace('T', ' ').slice(0, 16);

/* returned value: (String) 2014-07-28 18:26 */ / *返回值:(String)2014-07-28 18:26 * /

or even: 甚至:

(new Date(1406571989450)).toISOString().replace('T', ' ').slice(0, 16);

/* returned value: (String) 2014-07-28 18:26 */ / *返回值:(String)2014-07-28 18:26 * /

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM