Date Time Manipulation using JavaScript

In this example, I will show you have to perform some date time manipulations in JavaScript. By default, dates are stored in milliseconds. So to find the difference between the current date and a future one, you need to convert these milliseconds into weeks, days, hours, minutes, seconds and so on.

We will build a simple program that will show us the time left between the present day and New Year

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Time left till New Year (from Devcurry.com)</title>
<script type="text/javascript">
   1:  
   2:         var dtToday = new Date();
   3:         var dtYear = dtToday.getFullYear();
   4:         var dtLastDoy = new Date("December 31, " + dtYear);
   5:         var timeLeft = dtLastDoy.getTime() - dtToday.getTime();
   6:  
   7:         // Convert milliseconds into weeks, days, hours and minutes
   8:         var weeks = Math.floor(timeLeft / (1000 * 60 * 60 * 24 * 7));
   9:         var days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
  10:         var hours = Math.floor(timeLeft / (1000 * 60 * 60));
  11:         var minutes = Math.floor(timeLeft / (1000 * 60));
  12:  
  13:         var msg = "Only " + "<b>" + weeks + " weeks </b> or "
  14:                            + "<b>" + days + " days  </b>or "
  15:                            + "<b>" + hours + " hours  </b>or "
  16:                            + "<b>" + minutes + " minutes  </b>" 
  17:         + "left till New Year! ";
  18:         document.write(msg);
  19:     
</script>
</head>
<body>
<br /><br />
</body>
</html>


As you will observe, we first find the time difference between today’s date and the last day of the year, and store it in the ‘timeLeft’ variable (milliseconds). We then convert milliseconds into weeks, days, hours and minutes and display it on the page.

OUTPUT

image

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

pm said...

THANK YOU. i've scrubbed the web for a simple, straightforward script - also counting down 'weeks', which very few do - and yours as absolutely the best.