Formatting a date is giving me a different one from the passed one

Viewed 64

I need to get the first and last day of the current month, this works perfectly but when I format the date to looks like this yyyy/mm/dd it changes from the one I passed

For example, if a passed the 1 May 2020 when I format the date returns me the 30 April 2020

var startID = document.getElementById('start');
var datenow = new Date();
var firstday = new Date(datenow.getFullYear(), datenow.getMonth(), 1);
firstday = firstday.toISOString().slice(0, 10);
startID.value = firstday;
<input type="date" name="start" class="form-control" id="start" required autofocus>
<label for="start">Start Date</label>

This is how I get the first day of the current month:

var datenow = new Date();
var firstday = new Date(datenow.getFullYear(),datenow.getMonth(), 1);

This is how I format the date to looks like yyyy/mm/dd in this part is where I get another wrong date from the passed one:

firstday = firstday.toISOString().slice(0,10);
4 Answers

The root cause of the problem is in the use of getMonth() method to obtain the month number.

The getMonth() method returns integers from 0 to 11 (January = 0, ...Dec = 11).

The problem can be fixed by adding 1 to getMonth().

Here is a working example to show current date, first day and last day:

var now = new Date()
console.log("Today = " + now)

let month = (now.getMonth() + 1)
let year = now.getFullYear()

firstDay = ("1/" + month + "/" + year)
lastDay = ((new Date(year, month, 0)).getDate() + "/" + month + "/" + year)

console.log("First day = " + firstDay)
console.log("Last day = " + lastDay)

Output:

Today = Sat May 30 2020 20:54:56 GMT+0100 (British Summer Time)
First day = 1/5/2020
Last day = 31/5/2020

More information:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMonth

Timezones are tricky! Any given timestamp could look like a different date depending on your timezone. ISO strings ignore timezone. So for starters, you could just do new Date().toString().

That happens because firstday.toISOString() returns date in UTC timezone so if you're located somewhere else you can expect the shifts in dates.

Unfortunately there is no go-to solution if you're not using something like moment.js (and it does not seem to be appropriate for such a simple task). I'd recommend you something like:

const [day, month, year] = firstday.toLocaleDateString('en-US').split('.');
firstday = [year, month, day].join('/')

use moment.js to properly format dates and perform date related operations. it makes thing fairly easier to implement.

Related