我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
当然,您可以为日期字符串表示形式的每种变化构建特定的函数。如果您考虑国际日期格式,那么您会得到几十个名称荒谬且难以区分的特定函数。
没有匹配所有格式的合理函数,但有一个合理的函数组合:
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的函数参数来逐字地表示每个字符串日期表示。一切都是显式的和声明性的,也就是说,你几乎可以读到发生了什么。
其他回答
我不喜欢修改本机对象,而且我认为乘法比填充接受的解决方案的字符串更清楚。
函数yyyymmdd(dateIn) { var yyyy = dateIn.getFullYear(); var mm = dateIn.getMonth() + 1;// getMonth()是从零开始的 var dd = dateIn.getDate(); 返回String(10000 * yyyy + 100 * mm + dd);// mm和dd的前导零 } var today = new Date(); console.log(名称(今天));
小提琴:http://jsfiddle.net/gbdarren/Ew7Y4/
如果使用AngularJs(最多1.5),你可以使用日期过滤器:
var formattedDate = $filter('date')(myDate, 'yyyyMMdd')
根据@o-o的答案,这将根据格式字符串返回日期的字符串。如果你需要的话,你可以很容易地为年份和毫秒添加一个2位数的年份正则表达式。
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);
然而,我不知道这有多高效,特别是在性能方面,因为它使用了大量的正则表达式。它可能会使用一些我不掌握纯js的工作。
注意:我保留了预定义的类定义,但你可能想把它放在一个函数或自定义类根据最佳实践。
从ES6开始,你可以使用模板字符串使它更短:
var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
这个解决方案没有零垫。看看其他好的答案,看看如何做到这一点。
这个家伙这里=> http://blog.stevenlevithan.com/archives/date-time-format写了一个格式()函数Javascript的日期对象,所以它可以使用熟悉的文字格式。
如果你需要在应用程序的Javascript中使用完整的日期格式,请使用它。否则,如果你想做的是一次性的,那么连接getYear(), getMonth(), getDay()可能是最简单的。