/

Getting year-month-date from JS dates

Getting year-month-date from JS dates

If you ever find yourself in a situation where you need to extract only the year, month, and day from a JavaScript date object, here’s a simple solution.

Let’s say you want today’s date in the following format: 2023-01-20T07:00:00+02:00. You want the time portion (T07:00:00+02:00) to always remain the same, but the date part should reflect the current date.

The toISOString() method of the JavaScript Date object can give you the complete date and time in the following format: 2023-01-10T07:35:37.826Z. However, we only want the year, month, and day.

Instead of using methods like getFullYear() and others to extract the needed data, we can simply manipulate the string returned by toISOString().

Here’s the code snippet that accomplishes this:

1
`${new Date().toISOString().slice(0, 10)}T07:00:00+02:00`

By using slice(0, 10), we extract the characters from index 0 to 9 (which represents the year, month, and day) from the toISOString() string. Then, we append the fixed time portion (T07:00:00+02:00) to get the desired result.

This simple and concise approach will give you today’s date in the specific format you need.

Tags: JavaScript, date object, toISOString(), code snippet