Yesterday I needed to find a way to get Yesterday’s Date, Todays Date, and Tomorrows Date into a javascript array so that I can use it in a date picker carousel for a mobile phone application. The date picker allows you to swipe a calendar day to the left to pick tomorrows date, and when you swipe to the right you would get Yesterday’s Date. The carousel was inspired by Mateo Spinelli’s Swipeview: http://cubiq.org/swipeview
Coming from C#, you would think that you just use something like DateTime.Now().AddDays(-1) for Yesterday, DateTime.Now() for today, and DateTime.Now().AddDays(1) for tomorrow – right? Wrong..
It’s not that difficult, but it’s not something that’s obvious either. After digging around, I found references to the javascript Date() object, and all of its exposed methods. The first most straightforaward documentation I found was from here: http://www.elated.com/articles/working-with-dates/ . But then the rest of what I needed wasn’t available, which is how to increment a javascript variable by one day – without having to worry about the last day of the month… So after some digging, the key to the problem is the getTime() method. Get the time representation of the date object, and then add the necessary seconds (or milliseconds) to increment the date object by one day This discussion entry gave me the sample I needed: http://stackoverflow.com/questions/3674539/javascript-date-increment-question
 
Here is a sample:

 

<html>
<head>
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js”></script>
</head>
<body>
<div id=”b”></div>
<br>
<input type=”button” onclick=”SubtractDay()” value=”-“>
<input type=”button” onclick=”AddDay()” value=”+”>

lt;script language=”javascript”>
var oneday = 86400000; //24 * 60 * 60 * 1000;
var d = new Date();

function AddDay(){
d.setTime(d.getTime() + (oneday));
sethtml();
}

function SubtractDay(){
d.setTime(d.getTime() – (oneday));
sethtml();
}

function sethtml(){
$(‘#b’).html(d);
}

sethtml();
</script>
</body>
</html>