A Javascript tutorial on dates and times
Overview
Date and time play a crucial role in everyday programming tasks, and JavaScript offers a dedicated object called Date[1] to facilitate their manipulation. The Date object is designed to store both date and time information, providing various methods for effective operations. This guide aims to instruct you on working with the Date object in JavaScript, exploring its diverse options and aiding your comprehension of date and time functionalities.
Throughout the guide, we will delve into intricate yet fascinating use cases that have the potential to simplify your coding endeavors and enhance your productivity.
Requirements
A web browser with JavaScript support is required. For instance, you can easily access the JavaScript console in the Chrome browser by pressing CTRL+SHIFT+J. Once the console is open, you can execute commands and interact with JavaScript directly.
Creation of New Object in Javascript
To create a new Date object in JavaScript, use the following syntax: new Date(). This instantiates a Date object with the current time and date.
var now = new Date();
alert( now );
You can also create a new Date object by specifying the number of milliseconds that have elapsed since 1 January 1970, GMT+0. This can be achieved using the following syntax:
new Date(milliseconds)
To create a Date object representing a point in time 24 hours after 1 January 1970 GMT+0, you can use the following example:
var 24h1970 = new Date(3600 * 24 * 1000);
alert( 24h1970 );
If a string is the sole argument, the Date.parse method is employed to interpret the date from that string. This can be demonstrated with the following syntax:
new Date(datestring)
For example:
new Date(year, month, date, hours, minutes, seconds, ms)
You can create a Date object using components from the local timezone. When providing arguments to the Date constructor, only the first two (year and month) are mandatory. If other parameters are omitted, they default to zero, with the exception of the date parameter, which defaults to 1.
It’s important to note two things: the year must consist of four digits, and months are zero-indexed (January is 0, February is 1, and so on).
new Date(2011, 0, 1, 0, 0, 0, 0); - 1 of January 2011, 00:00:00
new Date(2011, 0, 1); - same, but hours and seconds are 0 by default Obtaining Time and Date
Get exact date with milliseconds:
var date = new Date(2011, 0, 1, 2, 3, 4, 567);
alert( date ); // 1.01.2011, 02:03:04.567
Getting date components:
getFullYear() - 4 digit year
getMonth() - get month, 0-11
getDate() - get month date, 1-31
getHours(), getMinutes(), getSeconds(), getMilliseconds() - get hours, minutes, seconds and milliseconds
IMPORTANT: always utilize getFullYear() instead of getYear() when working with dates. The latter is non-standard and may produce varying outputs across different browsers. It’s also worth noting that all the methods discussed above, including date creation and manipulation, provide results in the local timezone.
If you require working with dates in a different timezone, additional considerations and adjustments may be necessary.
There are also two specific non-UTC symbols: to obtain the number of milliseconds elapsed since 1 January 1970, GMT+0, you can use a method similar to the constructor new Date(milliseconds).
getTime()
To obtain the difference between local time and UTC time in minutes, you can use the getTimezoneOffset() method of the Date object:
getTimezoneOffset()
for example: alert( new Date().getTimezoneOffset() );
Establishing Time Components
setFullYear(year [, month, date])
setMonth(month [, date])
setDate(date)
setHours(hour [, min, sec, ms])
setMinutes(min [, sec, ms])
setSeconds(sec [, ms])
setMilliseconds(ms)
setTime(milliseconds)
There are also UTC counterparts for these methods:
setUTCFullYear(year [, month, date])
setUTCMonth(month [, date])
setUTCDate(date)
setUTCHours(hour [, min, sec, ms])
setUTCMinutes(min [, sec, ms])
setUTCSeconds(sec [, ms])
setUTCMilliseconds(ms)
setUTCTime(milliseconds)
Some methods, such as setHours, facilitate the simultaneous setting of multiple components. If a specific component is not provided, it remains unchanged.
var thisday = new Date;
thisday.setHours(0);
alert( thisday ); // today, but hours are changed to 0
thisday.setHours(0, 0, 0, 0);
alert( thisday ); // today, but time is 00:00:00 Automatic Date Correction
Auto-correction is a valuable feature of Date objects, allowing the object to rectify itself when incorrect values are set for certain components. For example:
var date = new Date(2014, 1, 32); // 32 of Februay 2014
alert(d) \\ it will be 4 of March 2014
Incorrect data components are automatically adjusted across other components. For instance, if you attempt to advance by 2 days from January 31, 2010, the Date object will auto-correct accordingly.
var td = new Date(2010, 0, 31);
td.setDate(td.getDate() + 2);
alert( td ); // 2 of February, 2010
It can also be employed to obtain a date that deviates from the current date by a specified amount. For instance, to get the date and time 60 seconds from the current moment, you can leverage this auto-correction feature.
var td = new Date();
td.setSeconds(td.getSeconds() + 60);
alert( d )
Zero and negative values are also supported, allowing for flexibility when working with Date objects.
var td = new Date;
td.setDate(1); // 1 day of month
alert( td );
td.setDate(0); // there is no 0 day, last day of previous month will be used
alert( td );
var td = new Date;
td.setDate(-1); // the day before the last day of previous month
alert( d ); Date Output and Formatting
All browsers, with the exception of IE10, support the new standard ECMA402[2], which introduces the toLocaleString method for formatting dates. This method allows for extensive customization using parameters like locale and options, providing a wide range of formatting possibilities.
var date = new Date(2013, 10, 29, 11, 29, 0);
var options = {
era: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long',
timezone: 'UTC',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
};
alert( date.toLocaleString("en", options) );
alert( date.toLocaleString("de-DE", options) );
It will return the date in both English and German when using toLocaleString(locale, options).
There are no localization methods for output in toString(), toDateString(), and toTimeString(). These methods provide a standard string output that is browser-dependent, with the sole requirement of being human-readable.
toString()returns the complete date and time.toDateString()returns only the date.toTimeString()returns only the time.
var td = new Date();
alert( td.toString() );
toUTCString()returns a string representation of the date and time in UTC, similar totoString().toISOString()returns the date in ISO format. It’s worth noting thattoISOString()is not supported in IE8.
var td = new Date();
alert( td.toISOString() );In Summary
Now you have a foundational understanding of how to work with date and time in JavaScript. While this guide doesn’t cover all aspects, it explores the most commonly used and interesting features of the Date() object, providing you with a solid starting point for incorporating it into your projects. For a more in-depth exploration, consider consulting the Mozilla Developer Network guide[3].
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
[2]: http://www.ecma-international.org/ecma-402/1.0/
[3]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
