2016-01-07 27 views
0

我有一個timeMachine函數,它需要5個參數,並告訴你輸入的時間之後是哪一天。但不是寫newDate.setDate(dateObject.getDate()+ daysLater);我想使用for循環來循環參數的長度並將輸入記錄到newDate中。我如何使用for循環將每個參數循環到newDate中?

var timeMachine=function(yearsLater,monthsLater,daysLater,hoursLater,minutesLater) { 
     var dateObject=new Date(); 
     var newDate=new Date(); 
     newDate.setDate(dateObject.getDate()+daysLater); 
     newDate.setMonth(dateObject.getMonth()+monthsLater); 
     newDate.setYear(dateObject.getFullYear()+yearsLater); 
     newDate.setHours(dateObject.getHours()+hoursLater); 
     newDate.setMinutes(dateObject.getMinutes()+minutesLater); 
     console.log(newDate); 
    } 
    timeMachine() 
+0

是否願意使用第三方庫來實現相同的功能? –

+0

@PeterWagener我還沒有學習所有的JavaScript,幾乎不知道任何第三庫。但當然! – Firefalcon1155

回答

0

這是不使用for循環,但我建議使用MomentJS任何基於日期的操作。從個人經驗來看,時間操縱很容易搞砸。

瞬間已經有這種內置的「時間機器()」功能,例如:

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日」或「11/20/15」或「2015/11/20」等)解析爲Moment對象。

基本上,除非你真的需要裸骨功能,否則不要自己做這個。站在巨人的肩膀上更容易。

+0

謝謝你的建議,我必須問的另外一件事情:我該如何改變解析香草JavaScript中的真實世界日期字符串? – Firefalcon1155

+0

@ Firefalcon1155意思是做一些像'new Date(「11/20/2015」)'?它在不同的瀏覽器中不一致。有關示例,請參閱http://dygraphs.com/date-formats.html。 –

+0

不,我的意思,而不是輸出是「星期五2017年1月06日GMT-0800(太平洋時間)」,我希望它像「2017年1月6日」 – Firefalcon1155