Thursday 22 December 2011

Some More Examples on difference between two dates using Javascript

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: 3 days left until Christmas!
Calculating time expired since the Millennium (Jan 1st, 2000)
<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: 4374 days has gone by since the millennium!
Dynamically indicating what's new on your page:
<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!

No comments:

Post a Comment