w3resource

JavaScript: Get the month start date

JavaScript Datetime: Exercise-52 with Solution

Write a JavaScript function to get the month's start date.

Sample Solution:

JavaScript Code:

// Define a function called startOfMonth that takes a Date object 'date' as input
function startOfMonth(date)
{
    // Create a new Date object representing the start of the month by using the year and month of the input date and setting the day to 1
    return new Date(date.getFullYear(), date.getMonth(), 1);
}

// Create a new Date object representing the current date and time
dt = new Date(); 

// Output the start of the month for the current date and time, converted to a string
console.log(startOfMonth(dt).toString());

Sample Output:

Fri Jun 01 2018 00:00:00 GMT+0530 (India Standard Time)

Explanation:

In the exercise above,

The code first defines a function called "startOfMonth()" which takes a "Date" object 'date' as input. This function creates a new "Date" object representing the start of the month of the given date. It achieves this by using the "getFullYear()" method to get the year of the input date, the "getMonth()" method to get the month of the input date, and setting the day to 1, effectively representing the first day of the month. Finally, it returns the newly created "Date" object.

The script then creates a new "Date" object called 'dt' representing the current date and time. It then calls the "startOfMonth()" function with 'dt' as an argument and outputs the result, which represents the start of the current month, converted to a string using the "toString(") method.

Flowchart:

Flowchart: JavaScript- Get the month start date

Live Demo:

See the Pen JavaScript - Get the month start date-date-ex-52 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript function to get the week end date.
Next: Write a JavaScript function to get the month end date.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.