我继承了我所在公司的一个项目。他们的日期以下列格式记录:
2011 年 3 月 18 日将列为“2011 年 3 月 18 日”。
2010 年 4 月 31 日将列为“2010 年 4 月 31 日”。
我如何使用 Javascript 将一天添加到以上述方式格式化的日期,然后将其重新转换回相同的格式?
我想创建一个将“2011 年 3 月 18 日”加一天并返回“2011 年 3 月 19 日”的函数。或者将“2011 年 6 月 30 日”加 1 天并返回“2011 年 7 月 1 日”。
谁能帮帮我?
最佳答案
首先没有 4 月 31 日 ;)
对于实际问题,日期对象作为参数传递时可以理解当前格式..
var dateString = '30 Apr 2010'; // date string
var actualDate = new Date(dateString); // convert to actual date
var newDate = new Date(actualDate.getFullYear(), actualDate.getMonth(), actualDate.getDate()+1); // create new increased date
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).substr(-2) + ' ' + newDate.toDateString().substr(4,3) + ' ' + newDate.getFullYear();
alert(newDateString);
演示在 http://jsfiddle.net/gaby/jGwYY/1/
相同的提取使用(更好的支持)slice
而不是 substr
// now extract the bits we want to crete the text version of the new date..
var newDateString = ('0'+newDate.getDate()).slice(-2) + ' ' + newDate.toDateString().slice(4,7) + ' ' + newDate.getFullYear();
关于javascript - 添加一天到 Javascript 日期 + 独特的格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6427113/