Skip to main content

Handling time & dates

In the previous chapter, we worked on using temporary data and arrived at a timeEntries dataset. This chapter will elaborate on how we can use the Date API to get the intended time/date format.

The JavaScript Date object is something we can use for this. 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. Below, you can see that by calling new Date() without passing arguments, the newly-created Date object represents the current date and time as of the time of instantiation, to which we can apply all the methods described here.

const currentDate = new Date();

const currentDayOfMonth = currentDate.getDate();
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getFullYear();

const dateString = `${currentDayOfMonth}-${currentMonth}-${currentYear}`;
console.log(dateString) // "22-02-2022"

This can be useful when comparing dates.

const currentDate = new Date("2023-01-28");
const previousDate = new Date("2023-01-01");

currentDate.getDate() === previousDate.getDate()
console.log(dateString) // false

However, below you can see we can also pass an argument, in this case an ISO-string, to the Date constructor, and then apply the same methods to the Date object as seen above to format our date:

const date = new Date("2022-02-22T22:22:22Z");
const dayOfMonth = date.getDate();
console.log(dayOfMonth) // "22"

const formattedTime = date.toLocaleTimeString("nl-NL", {
hour: "2-digit",
minute: "2-digit",
});
console.log(formattedTime) // "22:22"

const formattedDate = date.toLocaleDateString('en-GB', {
day: 'numeric',
month: 'short',
year: 'numeric',
});
console.log(formattedDate) // "22 Feb 2022"

Futher Reading