Understanding JavaScript Date Methods

Date creation, retrieval and representation are the most common operations in any software application. In JavaScript, Date objects are used for performing date operations.

What are JavaScript Date Methods?

JavaScript Date methods are used for creation, modification, parsing and formatting of a Date object. These methods include the ‘constructors’ to create a Date object, the ‘getters’ to retrieve the date information, the ‘setters’ to modify the Date object and ‘conversions’ to transform the date information in different formats.

In the last constructor one thing should be kept in mind: the ‘month’ argument is zero-based meaning ’0’ represents the month of January. The following code snippet demonstrates the use of JavaScript Date constructors.

In the above code snippet, the date object with current date is created. The call of ‘setFullYear’ method on Date object changes the year of the current date to ‘2015’ while the ‘setMonth’ method changes the zero based month part from current date object. Finally, ‘setDate’ changse the day of a month to ‘2’ and so on.

In most of the scenarios, a combination of JavaScript Date setter and getter is used. For example, you might need to add some days to a new registered user and set the resultant date as a trial period for that user. An example of this task is shown in the following code:

In JavaScript Date methods, UTC variants of getters and setters exist that return the results according to the universal time with the exceptions for ‘getTime’, ‘setTime’ and ‘getTimezoneOffset’ methods.

Formats in JavaScript Date Methods

JavaScript Date Getter methods are used to change the date and time of the Date object to different formats, results in a string. Following are the important ones.

‘toString ()’ converts the Date object into a string.

‘toDateString ()’ converts the’ date portion’ of a Date object into a string.

‘toTimeString ()’ converts the’ time portion’ of a Date object into a string.

In above code snippet ‘parse’ method of JavaScript Date is used to convert the date format in string to milliseconds and then a Date object is created with the returned milliseconds. If a ‘parse’ method failed to parse a string a ‘NAN’ value is returned.