Manipulate time and date values with JavaScript's Date object - Web Development - Techguide

Manipulate time and date values with JavaScript's Date object

 

Summary

Working with date values is a common task regardless of the language you use. When working with Web clients, JavaScript provides the Date object to work with date and time values. Learn more about the Date object in today's column.

Events

Echelon 2012
June 11 and 12, 2012

University Cultural Centre, National University of Singapore

Startup Asia Jakarta 2012
June 7 and 8, 2012

12th Floor, Annex Building, Wisma Nusantara Complex, Jl. M.H. Thamrin No. 59 Jakarta 10350, Indonesia

MMA Forum Singapore
April 23-25, 2012

Grand Hyatt Singapore

One of the trickier aspects of development is working with time and date values; it seems like each language or platform has its own format. With Web development, you can utilize server-side code to manipulate dates, or you can utilize JavaScript's Date object. In today's column, we take a closer look at this object.

Working with dates
It is simple to get going with time and date values in JavaScript. It begins with creating an instance of the Date object:

var d = new Date();

This returns an instance of the Date object in the variable d using the current date and time. The Date object includes numerous methods and properties for accessing and manipulating its value. The following list includes methods for accessing date values:

  • getDate(): Returns the day of the month.
  • getDay(): Returns the day of the week. The week begins with Sunday (0 - 6).
  • getFullYear(): Returns the four-digit year.
  • getMonth(): Returns the month.
  • getYear(): Returns the two-digit year.
  • getUTCDate(): Returns the day of the month according to the Coordinated Universal Time (UTC).
  • getUTCMonth(): Returns the month according to the UTC (0 - 11).
  • getUTCFullYear(): Returns the four-digit year according to the UTC.

Note: Wikipedia defines UTC as a high-precision atomic time standard which approximately tracks Universal Time (UT).

An important note regarding JavaScript and dates is it uses the number of milliseconds from midnight January 1, 1970 to store dates. This is called the epoch, and any dates and times before this date are not allowed.

Using the methods in the previous list is simple and straightforward as Listing A illustrates. One thing you will notice is the month and weekday values begin with zero, so you'll need to add one to them to display their actual values. You could easily use an array to display the actual day of the week's name. Listing B includes the JavaScript.

You are not restricted to working with the current date. The Date object may be initialized with a value passed to it, like this:

var d = new Date("date value");

Using this approach, we could alter the previous example to use a specific date. Listing C presents a simple way to discover the day of the week for a given value. The code produces the following output:

Today is: Wednesday 4/15/1979
UTC is: Wednesday 4/15/1979

Actually, there are four approaches to creating a Date object instance:

var d = new Date();
var d = new Date('July 4, 1976');
var d = new Date(7, 4, 1976);
var d = new Date(7, 4, 1976, 12,00,00);

We've covered the first two (notice that apostrophes or parentheses may be used). The final two use individual integer parameters using the following format (the time is optional):

var d = new Date(month, day,
year, hour, minutes, seconds);

Another way to populate a Date object is by way of the setDate method. It provides a way to reset a Date object's value or initialize it, but it requires an actual JavaScript Date object:

Var d1 = new Date();
var d2 = new Date("7/4/1976");
d1.setDate(d2.getDate());

There are more set methods for populating the various properties of the Date object, but let's cover time before discussing them.

Working with time
Along with the date components, the Date object stores time information as well. The following methods provide access to a Date object's time information:

  • getHours(): Returns the hour portion of the time.
  • getMinutes(): Returns the minutes portion of the time.
  • getSeconds(): Returns the seconds portion of the time.
  • getMilliseconds(): Returns the milliseconds portion of the time.
  • getTime(): Returns the number of milliseconds since midnight January 1, 1970.
  • getTimezoneOffset(): Returns the difference in minutes between local time and Greenwich Mean Time (GMT).
  • getUTCHours(): Returns the hour portion of the time according to UTC.
  • getUTCMinutes(): Returns the minutes portion of the time according to UTC.
  • getUTCSeconds(): Returns the seconds portion of the time according to UTC.
  • getUTCMilliseconds(): Returns the milliseconds portion of the time according to UTC.

As previously demonstrated, you can initialize a Date object by passing in the hours, minutes, and seconds, but the milliseconds property is set via the setMilliseconds method. This JavaScript displays the current time:

<script language="javascript">var d = new Date();
document.write(d.getHours() +
":" + d.getMinutes() + ":" + d.getSeconds() +
":" + d.getMilliseconds());
document.write(d.getTime());
</script>

It displays the following output:

12:36:33:41
1146760593041

The second value is a bit odd since it displays the number of milliseconds since January 1, 1970 to the value stored in the referenced Date object. It comes in handy when finding the difference between two values. As with date values, a setTime method is available as well:

Var dt1 = new Date();
var dt2 = new Date(1970, 4, 15);
dt1.setTime(dt2.getTime());

Setting properties
Like the setTime, setDate, and setMilliseconds methods, there are methods to populate all portions of a Date object. This includes the following:

  • setFullYear
  • setHours
  • setMinutes
  • setMilliseconds
  • setMonth
  • setSeconds
  • setUTCFullYear
  • setUTCMonth
  • setUTCHours
  • setUTCSeconds
  • setUTCMilliseconds

These methods allow you to easily reset a date property by passing in its new value. It's good to be able to work with and display dates, but there will be times when you need to perform calculations with dates and so forth.

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 milliseconds in a day (86400000) to present the result in day:

<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. 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.

Talkback

Add your opinion

In order to post a comment, you need to be registered. (Sign In or register below)

Post your comment

ZDNet Asia Live

The key for mobile operators is identifying the applications that are popular with subscribers on their network. They can then work partn...

1 hour ago by camcullen on Experience trumps content in apps monetization

Experience trumps content in apps monetization | ZDNet http://t.co/gBXcjbGd

Experience trumps content in apps monetization - ZDNet Asia News: "What we are doing currently is not to monetiz... http://t.co/S2EZtd8m

Malaysia organizations don't realize severity of cyberattacks: "Minister Maximus Johnity Ongkili said at the Sec... http://t.co/bgVlOBvx

#security Malaysia organizations don't realize severity of cyberattacks: "Minister Maximus Johnity Ongkili said ... http://t.co/hkFb4zrI

Malaysia organizations don't realize severity of cyberattacks http://t.co/EEEmRM3j via @zdnetasia

Malaysia organizations don't realize severity of cyberattacks - ZDNet Asia News http://t.co/YpNMYgb5

Malaysia organizations don't realize severity of cyberattacks http://t.co/FFems54Q

China solar cell makers seek Taiwan partnerships http://t.co/p5Hh7kJD

Big data acquisitions pave way to fast, effective innovation http://t.co/hdiEfBsz via @zdnetasia

Integration, focused investments to propel Windows Phone: By Kevin Kwang , ZDNet Asia on May 23, 2012 (2 hours a... http://t.co/E7tsZbHJ

Integration, focused investments to propel Windows Phone http://t.co/u9TqjQ8C

ZDNet Asia IT Salary Benchmark 2012 http://t.co/rVwYlV7H

AsiaClassifiedToday. Integration, focused investments to propel Windows Phone - ZDNet Asia: S... http://t.co/47tdjZyG #asia #google #biz

Malaysian organizations are apathetic about information security and fail to realize they are potentially under... http://t.co/XeuvbXrs

Big data acquisitions pave way to fast, effective innovation - ZDNet Asia News http://t.co/vDZpl0lu

So much as we know , MTK6575 extremely integrated frequency1GHz ARM Cortex-A9 processor, the superiority of 3G / HSPA Modem, and help the...

1 day ago by y15822137359 on 5 SaaS adoption speed bumps to avoid

I reckon your view: "CRM is strategy, not software", if a company replicating the approach uses in ERP implementation into CRM, what they...

2 days ago by wykoong on Gartner: Mobile CRM gives better ROI than social

This video will teach you about the Excel fill handle but also provide you with a workook to download... http://www.youtube.com/watch?v=...

3 days ago by TradeBrother on A quick fill handle trick for Microsoft Excel

waiting...

5 days ago by eapete on What should count in a company's market value?

Boy, you've opened a can of worms now.

Wait for the rants & raves.

5 days ago by eapete on What should count in a company's market value?

I was puzzling before this whether to replicate the success formula we executed for a financial institute, and come out with a standard s...

5 days ago by wykoong on Drop the egos, copy ideas, then innovate