The simplified way to work with dates in Javascript

Javascript

Working with dates in Javascript can be a little tricky. There are so many details that we have already created libraries (like Date-fns and Moment) to give us a hand.

But it’s not always necessary to use libraries. Using Javascript Date Object itself can actually be quite simple if you know what you are doing. In this post, I will guide you through the methods for working dates in javascript.

The Date Object

JavaScript offers us a functionality to work with dates through a powerful object: Date.

new Date();

By default, a new instance of the Date Object (without arguments) creates an object corresponding to the current date and time. The date will be created according to your computer system settings.

Internally, the dates are expressed in milliseconds since January 1, 1970 (UTC). This date is important because, as far as computers are concerned, that is where it all started.

To demonstrate, let’s create an instance of the JavaScript Date object, create a variable, and assign the current date to it. This article is being written on Tuesday, June 16th in Sydney (GMT+10), so it is the current date, time, and time zone that is represented below:

// Set variable to current date and time
const now = new Date();

console.log(now);
// Tue Jun 16 2020 09:03:11 GMT+1000 (Australian Eastern Standard Time)

You may already be familiar with timestamp UNIX: which represents the number of seconds that have passed since that famous date.

Important to say, the UNIX timestamp is given in seconds. JavaScript Date is given in milliseconds.

JavaScript, however, understands the date based on a timestamp derived from Unix time. We can get the timestamp with the getTime() method.

console.log(now.getTime());
//1592262461187

If we have a UNIX timestamp, we can instantiate a JavaScript Date object using it:

const timestamp = 1592262818;
const whichDay = new Date(timestamp * 1000);

console.log(whichDay);
//Tue Jun 16 2020 09:13:38 GMT+1000 (Australian Eastern Standard Time)

As you can see, they are the same date in both examples, with a difference of a few minutes. Because the clock never stops.

So to summarize this talk about timestamps, a UNIX timestamp is given in seconds and the Javascript Date object works with milliseconds.

Tue Jun 16 2020 09:13:38 GMT+1000 (Australian Eastern Standard Time)

//timestamp in seconds  -> 1592262818
//timestamp in milliseconds  -> 1592262461187

//The second value is accepted for Javascript Date object

Creating dates in Javascript

So far, we have learned how to create a new instance of Date based on the current time, and how to create one based on a timestamp. In total, there are four formats by which you can create new dates in JavaScript.

In addition to the current time, (instantiating the Date object without arguments), or passing a timestamp in milliseconds, you can also use, or specify dates in string format or specify each particular value for your Date Object.

  • new Date()
  • new Date(timestamp)
  • new Date(String)
  • new Date(year, month, day, hours, minutes, seconds, milliseconds)

To demonstrate the different ways of referring to a specific date, we will create new Date objects that will represent June 23, 1912, at 12:30 GMT in three different ways. The reason for that date.

// June 23th,1912 at 10h30 GMT

// Timestamp method
console.log(new Date(-1815348600*1000));
//Sun Jun 23 1912 10:30:00 GMT+1000 (Australian Eastern Standard Time)

// Date string method
console.log(new Date("June 23 1912 10:30"));
//Sun Jun 23 1912 10:30:00 GMT+1000 (Australian Eastern Standard Time)

// Date and time method
console.log(new Date(1912, 5, 23, 10, 30, 0, 0));
//Sun Jun 23 1912 10:30:00 GMT+1000 (Australian Eastern Standard Time)

The Unix timestamp for this date is: -1815348600. As you may have noticed, the number is negative. If the date is before 01/01/1970 it becomes negative.

The three examples above all create a date containing the same information.

In the date and time method, our seconds and milliseconds are set to 0. If any number is missing in the Data creation, it will be set to 0. However, the order cannot be changed, so keep this in mind if you decide to leave a number out.

You must have noticed that the month of June is represented by 5, not the usual 6. This is because the date and time numbers start from 0, as most programming languages do, e.g. Arrays.

Retrieving Data with get

Once we have a date, we can access all the components of the date with one of several methods built into the Date object. Important to notice:

  • The methods will return each part of the date in relation to the local time zone.
  • Each of these methods starts with get, and will return the relative number.
MethodReturnExample
getFullYear()YYYY1999
getMonth()0-110 = January / 11 = December
getDate()1-311 = First day of the month
getDay()0-60 = Sunday / 6 = Monday
getHours()0-230 = Midnight / 12 = Midday
getMinutes()0-59
getSeconds()0-59
getMilliseconds()0-999
getTime()Milliseconds since Epoch time

Let’s start by creating a new Javascript Date object, I’ll use the Data String method, but you can use any other.

const myDate = new Date("June 23 1912 10:30");

console.log(myDate.getFullYear()); 	 // 1912
console.log(myDate.getMonth());    	 // 5
console.log(myDate.getDate());	   	 // 23
console.log(myDate.getDay());            // 0 
console.log(myDate.getHours());    	 // 10
console.log(myDate.getMinutes());        // 30
console.log(myDate.getSeconds());        // 0
console.log(myDate.getMilliseconds());	 // 0
console.log(myDate.getTime());           // -1815348600000

Only with these methods, you can start playing around with dates in Javascript. we have already managed to create some small programs, for example, this code below shows the day of the week in full for the user:

const now = new Date();

switch (now.getDay()) {
   case 0:
      console.log("Today is Sunday - Go Rest");
      break;
   case 1:
      console.log("Today is Monday - Go Coding");
      break;
   case 2:
      console.log("Today is Tuesday - Go Coding");
      break;
   case 3:
      console.log("Today is Wednesday - Go Coding");
      break;
   case 4:
      console.log("Today is Thursday - Go Coding");
      break;
   case 5:
      console.log("Today is Friday - Go Coding");
      break;
   case 6:
      console.log("Today is Saturday - Go Rest");
      break;
   default:
      console.log("You don't live on earth");
      break;
}

The methods embedded in the Javascript Date object that start with get allow us to access date components and return the number associated with what we are retrieving from the instanced object.

Changing the Date with set

For all the methods we learned above, there is a corresponding set of methods. Where get is used to retrieve a specific component of dates in javascript, set is used to modify the components of dates in javascript. Note in the table below all the set methods that the Date Object offers us.

MethodReturnExample
setFullYear()YYYY1999
setMonth()0-110 = January / 11 = December
setDate()1-311 = First day of the month
setDay()0-60 = Sunday / 6 = Monday
setHours()0-230 = Midnight / 12 = Midday
setMinutes()0-59
setSeconds()0-59
setMilliseconds()0-999
setTime()Milliseconds since Epoch time

We can use these methods to modify one or all of the components of dates in Javascript. For example, we can change the year of our variable from the first example by simply doing so:

const myDate = new Date("June 23 1912 10:30");

myDate.setFullYear(1900);	

console.log(myDate);

And we just put another 12 years on this guy’s account.

A more elaborate example using dates in Javascript, if you want to know which day of the week will be on a specific date of the current month, you can do so:

const myDate = new Date("June 23 1912 10:30");

myDate.setFullYear(1900);	

console.log(myDate);

Internal methods that begin with set allow us to modify different parts of a Date object. You can change any of the properties of dates in Javascript.

Bottom Line

In this tutorial, we learn how to create an instance of the Data object, and use its internal methods to access and modify date components in Javascript.

Knowing how to work with dates in Javascript is essential for many common tasks, as it can allow you to do many things, from setting up a report to displaying dates and times in the correct time zone.

Well, I hope that you enjoyed it. See you next time!

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Comments