Tuesday, 1 June, 2021 UTC


Summary

Introduction

Whether you are creating a daily routine app, your own blog, or most any other type of dynamic web app, you will probably need to work with dates. In this article, we're going to learn how to get the current date in JavaScript, so you can successfully develop your applications. In JavaScript, there is a plethora of options to choose from, but the main class being used is Date(). It has a lot of methods and how you use it will depend on the format of the date you want to get. Afterwards, I will show you a popular JavaScript library that can be used for formatting time in general, and not just dates.

Using the Date() class

So as I previously mentioned, Date() is a go-to class in JavaScript when talking about time. There are a couple of approaches to this:
  • Using getDate, getMonth, and getFullYear methods
  • Using toJson method
  • Using toISOString, toUTCString and toLocaleDateString methods
  • Using now method

Using getDate, getMonth and getFullYear methods

Note for getDate method: The first thing to notice when using this approach is that we use getDate and not getDay. The reason is that the getDay method returns the day of the week, so since it's Friday now as I'm writing, the getDay method would return 5. The method getDate actually does what we need in this case, it returns the day of the month number. So for me, right now the day of the month is 21 (because it's 21.05.2021.). These methods are easily confused, so I wanted to give a heads up.
Note for getMonth method: Another thing to watch out for is that the month indexes start from 0, so January is 0, February is 1, etc. Basically, when we retrieve the month number, we need to add 1.
Now that we got the potential problems out the way, let's code:
let date = new Date()
let day = date.getDate();
let month = date.getMonth()+1;
let year = date.getFullYear();

let fullDate = `${day}.${month}.${year}.`;
console.log(fullDate);
At first, we instance the class Date and for each part of the date, we use a variable to break it out and inspect each.
We placed each method result in a separate variable and then used string interpolation to create a complete date. String interpolation is when we pass variables to string; in JavaScript this is achieved between back-ticks ( `` ) and variables are placed in ${variableName}. If you don't prefer string interpolation, the other way around this is to simply concatenate (add) strings together like this:
let fullDate = day + "." + month + "." + year + ".";
Our results will be the same in each case:
21.5.2021. // string interpolation
21.5.2021. // string concatenation
Say you want to show month as 05 and not 5. Unfortunately JavaScript's built-in Date class doesn't have many options for formatting dates to strings like other libraries do. So in this case we'll need to do the formatting ourselves, which we can do with some of JavaScript's method on strings, like padStart(length, substring). What it does it 'pads' (puts before) our string with thesubstring, until it reaches length. So since we want to make 05 from 5, we want to pad our string with "0" until it reaches length 2. Before all that, we need to cast date.getMonth()+1 to type String. Casting is explicitly changing a variable's type from one to the other. Here we change type number to type String. Our month variable will change to:
let month = String(date.getMonth()+1).padStart(2, "0");
This will change our date format to:
21.05.2021.

Using toJSON method

Previous method left space for date formatting; you could have a date like dd/mm/yyyy, dd-mm-yyyy, dd.mm.yyyy and all the other variations relating the order of day, month, and year. When using toJSON(), it returns a yyyy-mm-dd format alongside the time format, hh:mm:ss.ms.
Let's preview this approach:
let date = new Date().toJSON();
console.log(date);
This will output:
2021-05-21T13:42:07.553Z
You should see an output similar to this, but obviously your output will be different depending on when you ran the code. We see that we need only the date, which is first 10 characters, so let's use JavaScript's slice() method. Method slice(a, b) slices a string from point a to point b; in our example from 0 to 10. Let's try it:
let date = new Date().toJSON().slice(0, 10);
This will return:
2021-05-21
We can further slice this string, so we can arrange the parts to variables day, month and year, but it would be overdoing it, so if you need a different format, just use a different approach.

Using toISOString, toUTCString, and toLocaleDateString methods

Fun fact: toISOString() returns the exact same result as toJSON(), so we will skip it and go straight into toUTCString().
Using toUTCString:
let date = new Date().toUTCString();
console.log(date);
Will give us the output:
Fri, 21 May 2021 13:53:30 GMT
This format also returns date and time, with the addition of the day of the week. As I said in the toJSON() section, you could parse this result further, but it would probably be unnecessary since you have different approaches. Since we're only getting the date, we can slice this. Now there's no need for casting, because this is already a String:
let date = new Date().toUTCString().slice(5, 16);
This will give us the desired output:
21 May 2021
Using toLocaleDateString:
This method returns the date in a format corresponding to your system's language. It even has the option to pass the desired language as an argument and even simple date formatting options such as weekday, month, day, etc. We will divide this into 3 examples:
  1. Default options
    Let's see what happens when we call the method without any arguments:
    let date = new Date().toLocaleDateString();
    console.log(date);
    
    The output, for me, will be:
    5/21/2021
    
    This output depends on your locale, mine is US so the format will be as US date format.
  2. Passing only language preference
    If you want define a specific locale, you can pass it as a string argument, like so:
    let date = new Date().toLocaleDateString("fr-FR");
    console.log(date);
    
    The fr-FR is a locale code for France. You can find all the locale codes here.
    The French date format is dd/mm/yyyy, so the output will be:
    21/5/2021
    
  3. Passing both language preference and options
    Finally, let's go through the possible options. Only month and weekday can have a value of "long" or "numeric". Day and year can only be "numeric":
    • day
    • month
    • year
    • weekday
const dateOptions = { 
    day: 'numeric',
    month: 'long',
    year: 'numeric'
};

console.log(event.toLocaleDateString('fr-FR', dateOptions));
We will exclude weekday since we only need the date. This should output:
21 mai 2021
Now you learned a bit of French, as well.

Using now method

Method now() returns the number of milliseconds passed from January 1st, 1970 - which is the beginning of the Unix epoch in programming. If we pass the number of milliseconds to the Date constructor, we can get a ISO format date. Let's try it:
let time = Date.now()
console.log(time);
Which will output, again, for me:
1621608925212
Now if we pass that time to the constructor, as mentioned above, we can create a date object with that time:
let date = new Date(time);
console.log(time);
This will output:
2021-05-21T14:55:25.212Z
And we already know how to process this, using slice().

Using moment.js

This is just an alternative for using all the previous methods, a library made specifically for dates and times in JavaScript. You can visit their website here. Although this library has quite a few features, I will only go over how to create and do simple formatting for a date. Let's see how it works:
moment.format();
moment.format('Do MMMM YYYY');
moment.format('Do MMMM YY');
If you don't pass anything to format, you will get a ISO representation of the date, however, you can choose any format you want (and which is defined in Moment's documentation).
The code above will output:
2021-05-21T17:17:02+02:00
May 21st 2021
May 21st 21
This option is not the best if all you're looking for is retrieving the current date. This is because the Moment library is quite large and will bloat your JS code when used in front-end applications. On the other hand, if you need date and time manipulation or more advanced formatting, this is a great library.

Conclusion

There are numerous ways to retrieve a date in JavaScript, you just need to choose one that fits your use-case. For very simple needs, like creating a date or very simple formatting, then you can use the built-in Date class. If you need something a bit more complex with date and time, moments.js is a library to choose.