我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date
但我不确定是否值得只针对这个特定的任务。
其他回答
当然,您可以为日期字符串表示形式的每种变化构建特定的函数。如果您考虑国际日期格式,那么您会得到几十个名称荒谬且难以区分的特定函数。
没有匹配所有格式的合理函数,但有一个合理的函数组合:
const pipe2 = f => g => x => g(f(x)); const pipe3 = f => g => h => x => h(g(f(x))); const invoke = (method, ...args) => o => o[method] (...args); const padl = (c, n) => s => c.repeat(n) .concat(s) .slice(-n); const inc = n => n + 1; // generic format date function const formatDate = stor => (...args) => date => args.map(f => f(date)) .join(stor); // MAIN const toYYYYMMDD = formatDate("") ( invoke("getFullYear"), pipe3(invoke("getMonth")) (inc) (padl("0", 2)), pipe2(invoke("getDate")) (padl("0", 2))); console.log(toYYYYMMDD(new Date()));
是的,这是一大堆代码。但是,您可以通过简单地更改传递给高阶函数formatDate的函数参数来逐字地表示每个字符串日期表示。一切都是显式的和声明性的,也就是说,你几乎可以读到发生了什么。
new Date('Jun 5 2016').
toLocaleString('en-us', {year: 'numeric', month: '2-digit', day: '2-digit'}).
replace(/(\d+)\/(\d+)\/(\d+)/, '$3-$1-$2');
// => '2016-06-05'
这个家伙这里=> http://blog.stevenlevithan.com/archives/date-time-format写了一个格式()函数Javascript的日期对象,所以它可以使用熟悉的文字格式。
如果你需要在应用程序的Javascript中使用完整的日期格式,请使用它。否则,如果你想做的是一次性的,那么连接getYear(), getMonth(), getDay()可能是最简单的。
这个帖子中最受欢迎的答案的简化版本https://stackoverflow.com/a/3067896/5437379:
function toYYYYMMDD(d) {
var yyyy = d.getFullYear().toString();
var mm = (d.getMonth() + 101).toString().slice(-2);
var dd = (d.getDate() + 100).toString().slice(-2);
return yyyy + mm + dd;
}
似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date
但我不确定是否值得只针对这个特定的任务。