Home > Java Scripts Examples and Tutorials > Calculating the difference between two dates
India beat SL by four wickets
Maldives president resigns amid protests
UNP also protest at Hulftsdorp
Indian Coast Guard nabs 5 Lankan fishing boats
SL wins toss
SF brought to court
Get well soon, SLC tells Yuvi
We need democracy plus; Ranil
White flag appeal postponed
UNP DNA join hands in protest
India still ‘world class’ insists Mathews
SL to market Ayurveda drugs
Nine hand grenades found near Aluth Kade Court
Hirunika to join active politics
IPL teams splash the cash for Mahela and Murali
Anoma to lead protest to free SF
US diplomats heading to Sri Lanka
CID probing double murder in Kahawatta
Dr. R.H.S. Samaratunga appointed Sec to Petroleum Ministry
A/L fiasco - Probe team’s mandate limited
Are you in Love?
10 Top Sex Secrets Men won't Tell
Top 10 — Female Turn Ons
10 Commandments for good wives
How to live a happy and satisfied Life
Did I marry the right person?
Are You Happy
Alcohol makes men BETTER in the bedroom, scientists claim
Too busy for Love Making?
Have you gone off sex?
Love Isn't Blind
Are You A Lazy Lover?
5 Secret Relationship Resolutions
Are You Getting Attracted To Another Person?
Do you feel loved?
Calculating the difference between two dates
Calculating the difference between two dates in JavaScript is relatively straightforward, provided you choose the right Date methods to work with. Whichever way you get there, the potential applications on date differences are many, from counting down to a particular event, counting up from a past date, to dynamically indicating what's new on your page. Sounds like fun!
Lets begin this tutorial by getting to the heart of it:
Date.getTime()
For the scripts that follow, the above is our hero people, not some Hollywood actor. Date.getTime() is a prebuilt JS method that returns the time elapsed from January 1st, 1970 to the current Date instance, in milliseconds. Its superpower is not so much its long term memory, as impressive as that may be, but its knack for converting a date to a number (in milliseconds, but nevertheless). And we all know the easiest subjects to perform arithmetic on are numbers.
So here's the general premise for calculating the difference between two dates- convert both dates to a number using Date.getTime(), and subtract! To a few examples now.
Calculating days remaining until Christmas:
<script type="text/javascript"> //Set the two dates today=new Date() var christmas=new Date(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScript if (today.getMonth()==11 && today.getDate()>25) //if Christmas has passed already christmas.setFullYear(christmas.getFullYear()+1) //calculate next year's Christmas //Set 1 day in milliseconds var one_day=1000*60*60*24 //Calculate difference btw the two dates, and convert to days document.write(Math.ceil((christmas.getTime()-today.getTime())/(one_day))+ " days left until Christmas!") </script>
Example: 29 days left until Christmas!
Notice how the year for "Christmas" is dynamically set to the current year (or nextyear if Christmas has already passed for this year), so the script is reusable now and in the future as well without having to modify it.
Calculating time expired since the Millennium (Jan 1st, 2000)
We all remember the Millennium and perhaps even the parties we attended. The following shows how many days has elapsed since then (count up):
<script type="text/javascript"> //Set the two dates var millennium =new Date(2000, 0, 1) //Month is 0-11 in JavaScript today=new Date() //Get 1 day in milliseconds var one_day=1000*60*60*24 //Calculate difference btw the two dates, and convert to days document.write(Math.ceil((today.getTime()-millennium.getTime())/(one_day))+ " days has gone by since the millennium!") </script>
Example: 2522 days has gone by since the millennium!
Dynamically indicating what's new on your page:
Finally, how about displaying a "new" image alongside new content that will automatically disappear (the image, that is) after the specified future date has been reached? The logic is simple enough- if the current date is less than the specified future date, write out the "new" image:
<script type="text/javascript">
var newimage='<img src="news.gif">'
var today=new Date()
function whatsnew(yr,mon,day){
var expire=new Date(yr,mon,day)
if (today.getTime()<=expire.getTime())
document.write(newimage)
}
</script>
<!--"New" image will disappear after Dec 30th, 2002-->
<script>whatsnew(2002,11,30)</script> This is new content!Example: This is new content!
Conclusion
As you can see, it's not difficult at all to do arithmetic on dates in JavaScript, and in the process, derive a whole bunch of useful applications out of it.
Guidelines: You must register with a social media account such as Facebook, Twitter, Yahoo, etc. to comment on this story. Click on the "Login" button below to choose your login account of choice. We welcome your thoughts, but this is not an open forum. For the sake of all readers, please refrain from the use of obscenities, personal attacks or racial slurs. All comments must remain on topic and cyber bullying will not be tolerated. All comments are subject to our terms of service. Comments that do not comply may be removed. Repeat offenders will lose commenting privileges.
News Categories
Accidents and Incidents
Art and Society
Business and Finance
Education and Employment
Environment and Development
Help and Aid
Science and Technology
Security and Politics
Share Market and Exchange Rates
Sports and Entertainment
Tourism and Foreign Affairs
Women and Health
Information
Women and Health
Food Recipes
Love and Relationship
Web and IT
AJAX Examples and Tutorials
Java Scripts Examples and Tutorials
PHP Scripts Examples and Tutorials
Men want good-looking women
Making sex exciting
Duminda unmasked by Anarkali
Too busy for Love Making?
Srikanth Vandana got a Baby Boy-Father and Son Born on Same Day!
Anjali’s days with Bharathiraja and K. Balachandar
Have you gone off sex?
Sex and Shoes
Dirty Talk!
Happy Birthday Surya
Alcohol makes men BETTER in the bedroom, scientists claim
Sexless Marriages
Are You A Lazy Lover?
5 Secret Relationship Resolutions
Outsider Played Actress Sneha Hot Sexy Hip Cheap Photos?

































