我有一个timeMachine函数,它接受5个参数,并告诉你在输入之后的几天。但不是编写newDate.setDate(dateObject.getDate()+ daysLater);我想使用循环遍历参数的for循环' length并将输入记录到newDate中。
id | product_id | price | zdate
----+--------------------------------------+-------+---------------------
4 | 8da97d50-540e-4fdb-d032-7f443a9869a0 | 49 | 2015-03-14 11:27:00
5 | aa6d9976-e9ae-4478-486e-097e86c1e5fe | 109 | 2015-03-14 11:55:00
3 | b51654ea-6190-4ed2-5e23-7075ffd3b472 | 9 | 2015-03-14 11:01:00
(3 rows)
答案 0 :(得分:0)
这不是使用for
循环,但我建议使用MomentJS进行基于日期的操作。从个人经验来看,时间操纵很容易搞砸。
Moment已经内置了这种“timeMachine()”功能。例如:
var futureMoment = moment()
.add(yearsLater, 'years')
.add(monthsLater, 'months')
.add(daysLater, 'days')
.add(hoursLater, 'hours')
.add(minutesLater, 'minutes');
console.log(futureMoment.format()); // <<== get a formatted string
console.log(futureMoment.toDate()); // <<== 'toDate' gets the native Date object
它还有copious documentation,以及用于增加功能的良好插件。如果添加moment-parseformat,您可以轻松地将大多数真实日期字符串(即“2015年11月20日”或“2015年11月20日”或“2015/11/20”等)解析为Moment对象。
基本上,除非你真的需要裸骨功能,否则不要自己动手。站在巨人的肩膀上要容易得多。