Last updated on March 23rd, 2022 at 10:12 am

In this tutorial we are going to see how to provide a specific date and create a countdown script using Javascript. You are free to give any dates and the script will show you how many days left . It also has an option to show number of Minutes as well for granularity.

Complete Script

<script LANGUAGE='JavaScript'>
function days_between(date1, date2) {
var ONE_DAY = 1000 * 60 * 60 * 24
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
var difference_ms = Math.abs(date1_ms-date2_ms)
return difference_ms/ONE_DAY
}
var current_date = new Date()
var custom = 'Dec 31 2022'
var new_custom_date = new Date(custom)
var days_left = days_between(current_date, new_custom_date)
var time_left = days_between(current_date, new_custom_date)*24*60*60

// Write the result to the page
document.write('<h2>There are ' + time_left/60 + ' minutes left.That means '+ days_left +' days left for day '+custom+' to arrive</h2>')
document.write('<hr><h2><font color=red>With Math Round</font></h2></hr>')
document.write('<h2>There are ' + Math.round(time_left/60)+ ' minutes left.That means '+ Math.round(days_left) +' days left for day '+custom+' to arrive</h2>')
</script>

You just have to modify this variable named custom as per your requirement. The date format should be

  • Month – Short textual representation of a month, three letters, For example Jan, Dec etc.,
  • Day – Numeric representation of a month, with or without leading zeros, For example 01,1,02,2,3,03 etc,
  • Year – In full numeric representation of a year, 4 digits
var custom = 'Dec 31 2022'

Demo

In the demo you can see that we have 2 output one is without Math.round function and the other rounded to the nearest integer.

We are displaying the result using document.write. You can also make use of DOM by defining a div element inside your HTML code.

<div id='timer'></div>

Instead of the document.write section after defining the div, add this code

<script>
document.getElementById('timer').innerHTML='<h2>There are ' + time_left/60 + ' minutes left.That means '+ days_left +' days left for day '+custom+' to arrive</h2><hr><h2><font color=red>With Math Round</font></h2></hr><h2>There are ' + Math.round(time_left/60)+ ' minutes left.That means '+ Math.round(days_left) +' days left for day '+custom+' to arrive</h2>'
</script>

Similar CountDown Scripts

Javascript count down script for Christmas and NewYear Part 1 (This basically has the countdown with live timer)

Javascript Countdown script for Christmas or NewYear Part 2 (This basically has the countdown with live timer)

Countdown timer before displaying download link

Beautiful Christmas countdown timer complete webpage with css download free

2 thoughts on “How to create Countdown timer using Javascript”

Leave a Reply

Your email address will not be published. Required fields are marked *