1

I want user to enter a date. Using a form, and in the background convert this to number of days. Then desuct a certain number of days, then convert that back to a date.

Example:

Enter the date you were born.

-- convert to xx amount of days (dateindays)

Then make newtotal=dateindays-280

convert newtotal to a date.

Can anyone point me in the right direction of doing this, or do they know some function for doing this?

So lets say :user enters date 13th July 1980 We use js to convert this to total number of days 11,453 days

Then create new function : subtotal=11453-280

And convert those number of days into a date, and echo back on screen.

422
  • 5,714
  • 23
  • 83
  • 139

3 Answers3

3

use Date object. Use millis to do the conversion. So if you get the date millis and then subtract or add days * 86400 * 1000 and then create another date object with the result.

var d2 = new Date (d1.getTime() - days_to_subtract * 86400 * 1000);

This might help... http://www.w3schools.com/jsref/jsref_obj_date.asp

Sid Malani
  • 2,078
  • 1
  • 13
  • 13
  • Yer I get that, thanks. What I dont get is how I can then reconvert "time" back into a readable date. – 422 Nov 20 '11 at 23:11
  • Sorry please clarify the question. If you have a date object you should be able to display what you want right?? or am i missing something – Sid Malani Nov 20 '11 at 23:13
  • you can use toDateString() method on the date object. – Sid Malani Nov 20 '11 at 23:13
  • 2
    .getMilliseconds should be .getTime. To convert a Date to time, use .toString/.toDateString or construct something from the various getters. – themel Nov 20 '11 at 23:14
3
var d1 = Date.parse("13 July 1980");
d1 = d1 - 24192000000; // 280 days in milliseconds

var newDate = new Date(d1);

console.log(newDate); // will return a date object that represents Oct 07 1979

Then use the following link to format it: http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3

Thanks to this SO question for the link: Where can I find documentation on formatting a date in JavaScript?

Community
  • 1
  • 1
Chris
  • 54,599
  • 30
  • 149
  • 186
2

Why the conversion to and from days? To add or subtract days, just add or subtract them from the date:

// New date object for 15 November, 2011
var d = new Date(2011, 10, 15);

// Add 5 days
d.setDate(d.getDate() + 5);  // 20-Nov-2011

// Subract 200 days
d.setDate(d.getDate() - 200); // 4-May-2011
RobG
  • 142,382
  • 31
  • 172
  • 209