JavaScript - Date Object




JavaScript - Date Object

Programming languages contain useful constructs to make our lives easier. The JavaScript Date object is one such thing. It offers convenient methods to get the current date and time, store a date in a variable, perform date arithmetic and format the date based on the user’s locale. Due to differences between browser implementations and incorrect handling of DayLight Savings Time(DST), depending on the Date object for mission-critical applications is not recommended and you should probably be using a DateTime library like moment. But for educational purposes, we will use the methods that the Date() object provides to learn how JavaScript handles DateTime.

Getting Current Date

var currentDate = new Date();

If you don’t pass anything to the Date constructor, the date object returned contains the current date and time. You can then format it to extract only the date part as follows -

var currentDate = new Date();

var date = currentDate.getDate();
var month = currentDate.getMonth(); //Be careful! January is 0 not 1
var year = currentDate.getFullYear();

var dateString = date + "-" +(month + 1) + "-" + year;

Getting the Current Timestamp

If you instead want to get the current timestamp, you can create a new Date object and use the getTime() method.

var date = new Date();
var timestamp = date.getTime();

If you don’t intend to support <IE8, you can use Date.now() to directly get the timestamp without having to create a new Date object.

Parsing a Date

Converting a string to a JavaScript date object is done in different ways. The Date object’s constructor accepts a wide variety of date formats -

var date = new Date("Wed, 27 July 2016 13:30:00");
var date = new Date("Wed, 27 July 2016 07:45:00 GMT");
var date = new Date("27 July 2016 13:30:00 GMT+05:45");

Note that you do not need to include the day of week because JS can determine the day of the week for any date. You can also pass in the year, month, day, hours, minutes and seconds as separate arguments -

var date = new Date(2016, 6, 27, 13, 30, 0);

Of course, you can always use ISO date format -

var date = new Date("2016-07-27T07:45:00Z");

However, you can run into trouble when you do not provide the timezone explicitly.

var date = new Date("25 July 2016") // or
var date = new Date("July 25, 2016")

gives you 25 July 2016 00:00:00 local time.

If you use the ISO format, even if you give only the date and not the time and timezone, it will automatically accept the timezone as UTC.

new Date("25 July 2016").getTime() !== new Date("2016-07-25").getTime()
new Date("2016-07-25").getTime() === new Date("2016-07-25T00:00:00Z").getTime()

What is an JavaScript Date Object ?

In this article, we will learn about the Javascript Date Object. Date Object stores the date-time and also provides methods for working with them. In Javascript, the Date is stored as the number of milliseconds elapsed since 1st January 1970 midnight. This date is also known as UNIX Epoch.

We use the new keyword to create a Date Object. There are several ways to create Javascript dates using the Date Object -

new Date()
new Date(milliseconds)
new Date(date string)
new Date(year, month, date, hours, minutes, seconds, milliseconds)

new Date()

new Date() without any arguments will return the current date-time.

let date = new Date();
console.log(date);
//return current date-time
// format: Thu May 14 2020 00:41:03 GMT+0530 (India Standard Time)

new Date(milliseconds)

new Date(milliseconds) creates a Date object with date-time equal to the total number of milliseconds elapsed since 1st January 1970 UTC+0. The time elapsed in milliseconds from 1st January 1970 is known as a timestamp.

let unixEpoch = new Date(0);
console.log(unixEpoch);
// Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)

let unixEpochAnd2Days = new Date(2 * 24 * 3600 * 1000);
console.log(unixEpochAnd2Days);
// Sat Jan 03 1970 05:30:00 GMT+0530 (India Standard Time)

To create a Date object with a date earlier than 1st January 1970, we pass negative timestamp to the Date constructor.

let ADayBeforeUnixEpoch = new Date(- 24 * 3600 * 1000);
console.log(ADayBeforeUnixEpoch);
// Wed Dec 31 1969 05:30:00 GMT+0530 (India Standard Time)

JavaScript date objects can display date and time in differing formats, depending on the level of detail you aim to include. Dates are incorporated by using JavaScript get current date and JavaScript current time properties. This tutorial will help you master JavaScript date object properties and features, and explain how the JavaScript date to string function can transform the content of date objects into strings. When you finish this chapter, we suggest following up with JavaScript date methods tutorial.

JavaScript date object allows you to work with milliseconds, seconds, minutes, hours, days, months, and years. JavaScript date object can display a date in various formats. Date methods allow you to set years, months, days, hours, minutes, etc. If you are getting or setting a date without defining the time zone, the time will be chosen according to the browser's time zone. To learn more about JavaScript get current date and other properties, you should follow-up with the JavaScript Date Methods tutorial.

Date Methods

The following table lists the standard methods of the Date object.

For Example
Method Description
getDate() Returns the day of the month (from 1-31).
getDay() Returns the day of the week (from 0-6).
getFullYear() Returns the year (four digits).
getHours() Returns the hour (from 0-23).
getMilliseconds() Returns the milliseconds (from 0-999).
getSeconds() Returns the seconds (from 0-59).
getUTCHours() Returns the hour, according to universal time (from 0-23).
getUTCDate() Returns the day of the month, according to universal time (from 1-31).
getUTCHours() Returns the hour, according to universal time (from 0-23).
getYear() Deprecated. Use the getFullYear() method instead.

Common Date Methods

The date object can either get or set times and can compare times.

I am not going to show the examples here, but you should know that all of the date methods that get time return integers. If it was monday getDay() would return 1 instead of Monday (Sunday returns 0).

getFullYear() – gets the year (Ex. 2012)

getMonth() – gets the month, where January is 0 and December is 11

getDate() – gets the day of the month

getDay() – gets the day of the week, where Sunday is 0 and Saturday is 6

getHours() – gets the hour

getMinutes() – gets the minutes

getSeconds() – gets the seconds

getMilliseconds() – gets the milliseconds, remember that there are 1000 milliseconds in a second

Example

<script type="text/javascript">
    var d = new Date();
    document.write(d.getDay());
</script>

Result

3

2

Comparing Times

Setting and getting times are extremely useful, but what if you want to compare them?

Example

<script type="text/javascript">
    var oldTime = new Date(2012,3,1,20,28,56,445);
    var nowTime = new Date();
    if(oldTime.getTime() <= nowTime.getTime())
    {
        document.write("nowTime is greater than oldTime");
    }
    else
    {
        document.write("oldTime is greater than nowTime");
    }
</script>

Result

nowTime is greater than oldTime