DEV Community

loading...
Cover image for 3 tips for working with dates using vanilla JS

3 tips for working with dates using vanilla JS

Nancy
PhD drop out | Turning JavaScript/HTML/CSS from hobby to career | she/her My raw "Today I Learned" notes: https://nancyhuynh-til.netlify.app/
・2 min read

Ok, first off, I know that moment.js exists and I do use it. This article outlines a few tricks I learned by creating a calendar using the Date object (MDN web docs) in (vanilla) Javascript. These tips might be handy if you need to do one-off things with dates

Vanilla JS Calendar

First day of the month

Create a new date object with the current date, then set the day to 1 with setDate()

const startDate = new Date();
startDate.setDate(1);
console.log(startDate); // Date object representing first day of current month

Last day of the month

Since the last day of the month can be different (28, 29, 30, 31 — ugh February!) this one isn't as straightforward. We first have to set the month to the next month and then call setDate() with 0

const endDate = new Date();
endDate.setMonth(endDate.getMonth() + 1);
endDate.setDate(0);
console.log(endDate); // Date object representing last day of current month

Formatting dates

With the Intl.DateTimeFormat (MDN web docs) object it is really easy to format dates—and you can also format them for different languages too

const today = new Date();
const monthYearOpts = {
    month: 'long', 
    year: 'numeric'
}

const monthYearString = (new Intl.DateTimeFormat('en-US', monthYearOpts)).format(today);
const monthYearStringFrench = (new Intl.DateTimeFormat('fr-FR', monthYearOpts)).format(startDate);

const dayDateMonthOpts = {
    weekday: 'short', 
    day: 'numeric', 
    month: 'long', 
    year: 'numeric'
}
const dayDateMonth = (new Intl.DateTimeFormat('en-US', dayDateMonthOpts)).format(startDate);

console.log(monthYearString); // August 2020, for example
console.log(monthYearStringFrench); // août 2020, for example
console.log(dayDateMonth); // Sat, August 1, 2020, for example

It's worth noting that the level of customizing is not as granular as something like moment.js. For example Intl.DateTimeFormat automatically places in punctuation automatically based on the language and region.

Conclusion: Built-in Javascript objects work in a pinch for date manipulation and formatting

It's not as handy for more complex date manipulations but it works in a pinch of you need to do something simple. Even creating the Vanilla JS calendar was fairly straightforward

References

Discussion (0)