For any web developer, working with the date in the application is always a tricky part. While working with the date, we have to make sure things works properly for every timezone. In Javascript, you might have to work with the calendar events, booking events or any other type of events which needs the relevant times based on the user’s geolocation.

In this article, we are going to learn about the javascript date object in detail and what are the things which we have to take care while working with the javascript date object.

Javascript date object

The Date object is a built-in object in javascript that stores the date and time. Date objects are based on the time value that is the number of milliseconds since 1 January 1970 UTC.

There are many ways in which you can instantiate a date in Javascript. All of those methods work in your local time zone.

create date without arguments

let now = new Date();

The now variable will display the current date and time of your local zone.

create a date with strings

let date = new Date('2019-11-05');

In this method, you can create a date by passing the date-string into the new Date().

We explain date-string differently in different parts of the world. For example, 11-05-2019 is either 11th May, 2019 or 5th November 2019. This is very confusing and so in javascript, if you are using the date-string then you have to use the format which is accepted worldwide that is ISO 8601.

// ISO 8601 Extended format
`YYYY-MM-DDTHH:mm:ss:sssZ`
  • YYYY: the year in 4 -digit
  • MM: month in 2-digit where 01 indicates January and 12 indicates December
  • DD: the date in 2-digit(0-30)
  • -: Date delimiters
  • T: Indicates the start of time
  • HH: 24-digit hour (0 to 23)
  • mm: Minutes (0 to 59)
  • ss: Seconds (0 to 59)
  • sss: Milliseconds (0 to 999)
  • :: Time delimiters
  • Z: If Z is present, the date will be set to UTC. If Z is not present, it’ll be Local Time. (This only applies if time is provided.)

One point to note here while creating a date with date-string is you have to take care of the timezones.

What does this mean??? Let’s understand by an example which explains by CSS-tricks in one of their articles.

new Date('2019-11-05')

There’s a huge problem in the above date creation. You can spot the problem if you console.log this date.

If you live in an area that’s behind GMT, you’ll get a date that says 4th June and If you live in an area that’s ahead of GMT, you’ll get a date that says 5th June. This happens because the date-string method has a peculiar behaviour: If you create a date (without specifying time), you get a date set in UTC.

In the above scenario, when you write new Date(‘2019-11-05’), you actually create a date that says 5th November 2019, 12 am UTC. This is why people who live in areas behind GMT get a 4th November instead of 6th November.

If you want to create a date in Local Time with the date-string method, you need to include the time. When you include time, you need to write the HH and mm at a minimum.

Due to this issue, it is recommended to not use date-string for creating the date in javascript.

If you want to create dates, use arguments or timestamps which we are going to learn next.

create a date with arguments

// 5th Novemver 2019, 8:12:23pm, Local Time
let date = new Date(2019, 11, 5, 8 12, 23)

You can read above date from left-right as a year, month, date, hour, minutes, seconds.

In Javascript. the month is a zero-indexed so make sure while creating a date with this method.

All the date created with this method is in local time zone if you need to create date with UTC then you can do that by below method

let date = new Date(2019, 11, 5)

creating dates with timestamps

You can also crate date bypassing the timestamp value into the new Date() object.

let date = new Date(1572965652)

Javascript Date Object Prototypes

Getters

Date.getDate()

The getDate() method returns the day of the month for the specified date according to local time.

let date = new Date(2019,11,05);
console.log(date.getDate());

Date.getDay()

The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.

let date = new Date(2019,11,05);
console.log(date.getDay());

Date.getFullYear()

The getFullYear() method returns the year of the specified date according to local time.

let date = new Date(2019,11,05);
console.log(date.getFullYear());

Date.getHours()

The getHours() method returns the hour for the specified date, according to local time.

let date = new Date(2019,11,05);
console.log(date.getHours());

Date.getMinutes()

The getMinutes() method returns the minutes in the specified date according to local time.

let date = new Date(2019,11,05);
console.log(date.getMinutes());

Date.getSeconds()

The getSeconds() method returns the seconds in the specified date according to local time.

let date = new Date(2019,11,05);
console.log(date.getSeconds());

Date.getMilliseconds()

The getMilliseconds() method returns the milliseconds in the specified date according to local time.

let date = new Date(2019,11,05);
console.log(date.getMilliseconds());

Date.getTime()

The getTime() method returns the number of milliseconds* since the Unix Epoch. getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.

date = new Date(2019,11,05);
console.log(date.getTime());
Date/TimeMethodRange
YeargetFullYear()YYYY
MonthgetMonth()0-11 ( 0 => January, 11 => December)
Day of the MonthgetDate()1-31 ( 1 => 1st day of the month)
Day of the weekgetDay()0-6 ( 0=> Sunday, 1=> Monday and so on…)
HourgetHours()0-23 ( 0 => midnight)
MinutegetMinutes()0-59
SecondgetSeconds()0-59

Setters

Date.setDate()

The setDate() method sets the day of the Date object relative to the beginning of the currently set month.

let date = new Date('November 19, 2019 23:15:30');

date.setDate(24);

console.log(date.getDate());
// expected output: 24

date.setDate(32);
// Only 31 days in August!

console.log(date.getDate());
// expected output: 1

Date.setHours()

The setHours() method sets the hours for a specified date according to local time and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC until the time represented by the updated Date instance.

let date = new Date('November 19, 2019 23:15:30');
date.setHours(20);

console.log(date);
// expected output: Tue Nov 19 2019 20:15:30 GMT+0530 (India Standard Time)
// (note: your timezone may vary)

date.setHours(20,21,22);

console.log(date);
// expected output: Tue Nov 19 2019 20:21:22 GMT+0530 (India Standard Time)

Date.setMinutes()

The setMinutes() method sets the minutes for a specified date according to local time.

let date = new Date('November 19, 2019 23:15:30');
date.setMinutes(20);

console.log(date.getMinutes());
// expected output: 20

Date.setMonth()

The setMonth() method sets the month for a specified date according to the currently set year.

let date = new Date('November 19, 2019 23:15:30');
date.setMonth(12);

console.log(date.getMonth());
// expected output: 12

You can find all the getters and setters of JavaScript Date.prototype methods here.

Date/TimeMethodRange
YearsetFullYear()1970
MonthsetMonth()0-11 ( 0 => January, 11 => December)
Day of the MonthsetDate()1-31 ( 1 => 1st day of the month)
Day of the weeksetDay()0-6 ( 0=> Sunday, 1=> Monday and so on…)
HoursetHours()0-23 ( 0 => midnight)
MinutesetMinutes()0-59
SecondsetSeconds()0-59

Formatting Javascript Date Object

In Javascript, formating a date object is very difficult task. Like other programming languages there are no such way to format the date in Javascript.

Below is the 7 native formatting method in javascript to format the date:

Date.toDateString()

The toDateString() method returns the date portion of a Date object in English.

let date = new Date('November 19, 2019 23:15:30');
console.log(date.toDateString());
// expected output: Tue Nov 19 2019

Date.toString()

The toString() method returns a string representing the specified Date object.

let date = new Date('November 19, 2019 23:15:30');
console.log(date.toString());
// expected output: Tue Nov 19 2019 23:15:30 GMT+0530 (India Standard Time)

Date.toString() returns a string representation of the Date in the format specified in ECMA-262 which can be summarised as:

  • Week day: 3 letters English weekday name, e.g. “Sat”
  • space
  • Month name: 3 letters English month name, e.g. “Sep”
  • space
  • Date: 2 digit day in a month, e.g. “01”
  • space
  • Year: 4 digit year, e.g. “2018”
  • space
  • Hour: 2 digit hour of the day, e.g. “14”
  • colon
  • Minute: 2 digit minute of the hour, e.g. “53”
  • colon
  • Second: 2 digits second of minute, e.g. “26”
  • space
  • The string “GMT”
  • Timezone offset sign, either:
    • “+” for positive offsets (0 or greater)
    • “-” for negative offsets (less than zero)
  • Two-digit hour offset, e.g. “14”
  • Two-digit minute offset, e.g. “00”
  • Optionally, a timezone name consisting of:
    • space
    • Left bracket, i.e. “(“
    • An implementation-dependent string representation of the timezone, which might be an abbreviation or full name (there is no standard for names or abbreviations of timezones), e.g. “India Standard Time” or “IST”
    • Right bracket, i.e. “)”

Date.toLocaleString()

Date.toLocaleString gives you a date in the format of DD/MM/YYYY, hh:mm:ss

You can find full details here.

Date.toLocaleDateString()

Date.toLocaleDateString() returns a string with a locality-sensitive representation of the date portion of this date based on system settings.

Date.toUTCString()

This method converts a date into the string using the UTC time zone.

let date = new Date('November 19, 2019 23:15:30');
console.log(date.toDateString());
// expected output: Tue Nov 19 2019

Date.toISOString()

The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always zero UTC offset, as denoted by the suffix “Z”.

let date = new Date('November 19, 2019 23:15:30');
console.log(date.toDateString());
// expected output: 2019-11-19T17:45:30.000Z

Writing a custom date format in Javascript

Till now we see the native methods of formatting the Javascript date object which gives results in their own way. But what if you want to format the date like Wed, 6 Nov 2019. To create this value, we have to use the javascript getters method which we learned earlier like below example.

const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];

const days = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ];

const d = new Date(2019, 11, 06);

const year = d.getFullYear();

const date = d.getDate();

const monthIndex = d.getMonth();
const monthName = months[monthIndex];

const dayIndex = d.getDay();
const dayName = days[dayIndex];

const formatted = `${dayName}, ${date} ${monthName} ${year}`;
console.log(formatted); // Fri, 6 December 2019

Using the above technique, we can format date in javascript into any desired format. There is also a library which makes the handling of date into javascript very easy. You can use moment.js library if you application needs lots of work on a date.

Comparing two date object in Javascript

Sometimes in our application, we have to compare the two date objects. We can easily do that with >, <, >= and <=.

const earlier = new Date(2019, 10, 05)
const later = new Date(2019, 10, 06)

console.log(earlier < later) // true

But if you want to compare two date objects fall into same time or same day or same year then you can’t do that using the above method. For that, you have to use timestamp using the getTime().

const isSameTime = (time1, time2) => {
  return time1.getTime() === time2.getTime()
}

const time1 = new Date(2019, 10, 05)
const time2 = new Date(2019, 10, 05)

console.log(isSameTime(time1, time2)) // true

Conclusion

In this article, we learn how to use the javascript date object. What are the javascript date object built-in method and how to use them, how to format javascript date into the custom format and lots more.

After reading this article now you can easily work on date without using any third-party library like moment.js and others. But I will suggest, if your application depends mostly on the date then you must know how to use the moment.js to format the date into javascript.

In the meantime, if you have any suggestions or doubt feel free to comment it into the comment box.

Codecademy Web Development
Pin It