Finding the difference between two values

The easiest arithmetic is subtracting or adding two numbers (you may disagree), so finding the difference between two JavaScript date values is simple. You just find the difference and it returns the difference as a number. The result will be a date value in milliseconds, so you'll have to perform division to get the necessary value type (days, months, minutes, hours, etc.).

The following JavaScript calculates the number of days until a specific date. It subtracts the two date values (via getTime) and divides the result by the number of seconds in a day (86400000) to present the results in days:

<script type="text/javascript">
var d1 = new Date();
var d2 = new Date(2006, 6, 7);
var day = 1000*60*60*24;
var diff = Math.ceil((d2.getTime()-d1.getTime())/(day));
document.write("Days until vacation: " + diff);

</script>
Date arithmetic
The various properties of a Date value may be increased or decreased by adding or subtracting the necessary values via the appropriate property. For example, if you want to increase the value by one month, you would add one to the month property. The example in Listing D displays difference values for yesterday and tomorrow for the previous script.

Listing D

<script type="text/javascript">
var d1 = new Date();
var d2 = new Date(2006, 6, 7);
var day = 1000*60*60*24;
var diff = Math.ceil((d2.getTime()-d1.getTime())/(day));
document.write("Days until vacation: " + diff);
document.write("<br />");

d1.setDate(d1.getDate() + 1);

diff = Math.ceil((d2.getTime()-d1.getTime())/(day));
document.write("Tomorrow it will be " + diff + " days until
  vacation.");
document.write("<br />");

d1.setDate(d1.getDate() - 2);

diff = Math.ceil((d2.getTime()-d1.getTime())/(day));
document.write("Yesterday, it was " + diff + " days until
  vacation.");

</script>
The following output is displayed:
Days until vacation: 50
Tomorrow it will be 49 days until vacation.
Yesterday, it was 51 days until vacation.
The time has come
Working with date and time values has its quirks that vary by platform, and Web development is no different. The JavaScript Data object provides an easy way to work with date and time values, but there are things to remember like the numbering of weekdays and months and formatting of some methods. They are not hard to remember once you are accustomed to its approach. A good thing to remember is the accuracy of date or time depends on the accuracy of the clock on the computer from which the page is being viewed.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

This article was orginally published on TechRepublic.

Do you need help with Web Technologies? Gain advice from Builder AU forums

Related links

Comments

1

Sudip Dey - 05/03/08

codes are simple to understand....also give code which autorefresh the time....
I need your comments also....

<html>
<head>
<title>Digital Clock</title>
<style>
<!--
.styling{
background-color:black;
color:lime;
font: bold 15px MS Sans Serif;
padding: 3px;
}
-->
</style>
</head>

<body>
<span id="digitalclock" class="styling"></span>

<script>
<!--

/*****************************************
* LCD Clock script- by Javascriptkit.com
* Featured on/available at http://www.dynamicdrive.com/
* This notice must stay intact for use
*****************************************/

var alternate=0
var standardbrowser=!document.all&&!document.getElementById

if (standardbrowser)
document.write('<form name="tick"><input type="text" name="tock" size="6"></form>')

function show(){
if (!standardbrowser)
var clockobj=document.getElementById? document.getElementById("digitalclock") : document.all.digitalclock
var Digital=new Date()
var hours=Digital.getHours()
var minutes=Digital.getMinutes()
var dn="AM"

if (hours==12) dn="PM"
if (hours>12){
dn="PM"
hours=hours-12
}
if (hours==0) hours=12
if (hours.toString().length==1)
hours="0"+hours
if (minutes<=9)
minutes="0"+minutes

if (standardbrowser){
if (alternate==0)
document.tick.tock.value=hours+" : "+minutes+" "+dn
else
document.tick.tock.value=hours+" "+minutes+" "+dn
}
else{
if (alternate==0)
clockobj.innerHTML=hours+"<font color='lime'>&nbsp;:&nbsp;</font>"+minutes+" "+"<sup style='font-size:1px'>"+dn+"</sup>"
else
clockobj.innerHTML=hours+"<font color='black'>&nbsp;:&nbsp;</font>"+minutes+" "+"<sup style='font-size:1px'>"+dn+"</sup>"
}
alternate=(alternate==0)? 1 : 0
setTimeout("show()",1000)
}
window.onload=show

//-->
</script>
</body>
</html>

» Report offensive content

2

Linda - 01/10/08

As part of my job, I add an expiration date to secured spec. The date is to be 1 week from the day someone prints or opens a specific spec. My problem is that it only works on 98 computers and not XP. I inherited the code and am not too familar with JavaScrip. Can you tell me why this does not work on XP computers?
Thanks for you time.

/* Example of date arithmetic. */
/* Create a date object containing the current date. */
var d1 = new Date();
/* num contains the numeric representation of the current date. */
var num = d1.valueOf();
/* Add seven days to today’s date. */
/* 1000 ms / sec; 60 sec / min; 60 min / hour; 24 hours / day; 7 days */
num += 1000 * 60 * 60 * 24 * 7;
/* Create our new date that is 7 days ahead of the current date. */
var d2 = (new Date(num));
/* Add text. */
var d3 = "Document Expires:";
/* Print out the current date and our new date using util.printd */
var f = this.getField("Today1");
f.value = d3 +(util.printd("mm/dd/yyyy", d2));

» Report offensive content

Leave a comment

You must read and type the 6 chars within 0..9 and A..F

* indicates mandatory fields.

2

Linda - 10/01/08

As part of my job, I add an expiration date to secured spec. The date is to be 1 week ... more

1

Sudip Dey - 03/05/08

codes are simple to understand....also give code which autorefresh the time.... I need your comments also.... <html> <head> <title>Digital Clock</title> <style> <!-- .styling{ background-color:black; color:lime; font: bold 15px MS Sans ... more

Log in


Sign up | Forgot your password?

  • Chris Duckett IE9's H.264 vote killed Ogg

    In a split decision by the judges, the winner of the W3C/WHATWG video codec consensus is H.264, taking home the future of video playback on the internet while loser Ogg goes home with nothing but thoughts of what might have been. Read more »

    -- posted by Chris Duckett

  • Staff Google launches Apps Marketplace

    Google launches and app store, while Mozilla plans to re-write its open-source license. More of this week's news in the Roundup. Read more »

    -- posted by Staff

  • Staff Microsoft showcases new NUIs

    TechFest, Microsoft's internal even took place this week with researchers showcasing some new interfaces the company is working on. Read more »

    -- posted by Staff

What's on?

  • Optus Deal

    Broadband + home phone + PlayStation®3 in a single package price!