Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding one day to Javascript date + unique formatting?

I've inherited a project for a company I'm working for. Their dates are recorded in the following format:

March 18th, 2011 would be listed as "18 Mar 2011".

April 31st, 2010 would be listed as "31 Apr 2010".

How would I use Javascript to add one day to a date formatted in the above manner, then reconvert it back into the same format?

I want to create a function that adds one day to "18 Mar 2011" and returns "19 Mar 2011". Or adds 1 day to "30 Jun 2011" and returns "1 Jul 2011".

Can anyone help me out?

like image 621
Walker Avatar asked Jun 21 '11 14:06

Walker


1 Answers

First of all there is no 31st of April ;)

To the actual issue, the date object can understand the current format when passed as an argument..

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);

demo at http://jsfiddle.net/gaby/jGwYY/1/


The same extraction using (the better supported) slice instead of 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();

Demo at http://jsfiddle.net/jGwYY/259/

like image 197
Gabriele Petrioli Avatar answered Nov 16 '22 05:11

Gabriele Petrioli