Domanda

I am using the following function to add a number of days to a given date input (format: yyyy-mm-dd).

This works fine but does not add leading zeros when needed, e.g. it returns 2013-11-1 instead of 2013-11-01 which is what I need.

What would be the best / shortest way here to format the output as yyyy-mm-dd - jQuery would work too ?

 function calcTargetDate()
 {
     var timeFrame = 7;
     var targetDate = new Date( document.getElementById('date1').value );

     targetDate.setDate( targetDate.getDate() + parseInt(timeFrame) );
     document.getElementById('date2').value = ( targetDate.getFullYear() + '-' + (targetDate.getMonth() + 1) + '-' + targetDate.getDate() );
 }

Many thanks in advance for any help with this, Tim

È stato utile?

Soluzione

Is including a lib an option? moment.js could do this for you easily with something like:

var targetDate = moment( document.getElementById('date1').value );
targetDate.add('days', timeFrame); //or whatever unit your timeframe value is if not days
document.getElementById('date2').value = targetDate.format("YYYY-MM-DD");

Altri suggerimenti

For any date formatting I always use moment.js

 var myDate = new Date(2013, 10, 1); // remember month zero-indexed in javascript
 console.log(myDate);
 console.log(moment(myDate).format('YYYY-MM-D'));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top