Is there any way to get the first date of the month without using moment

Viewed 31
const startOfMonth = moment().startOf("month").format("x");

The output above is 1661961600000 My goal is to get the first date of the month without using moment

1 Answers

You can use the Date constructor, setting the year and month to the same as the given date, but with a date argument of one:

function getStartOfMonth(date) {
    return new Date(date.getFullYear(), date.getMonth(), 1)
}

console.log('Start of current month:', getStartOfMonth(new Date()).toString());
console.log('Start of current month (ms):', getStartOfMonth(new Date()).getTime());
.as-console-wrapper { max-height: 100% !important; }

Related