I start by getting the date of the beginning of month:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Then I convert it to ISO:
firstDay = firstDay.toISOString();
Why did I get 2019-05-31
as the first day instead of 2019-06-01
?
I start by getting the date of the beginning of month:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
Then I convert it to ISO:
firstDay = firstDay.toISOString();
Why did I get 2019-05-31
as the first day instead of 2019-06-01
?
-
1
You're converting the Date object to an ISO string, so you'll need to show the contents of
parseIDateFromString
– WilliamNHarvey Commented Jun 5, 2019 at 18:05 -
1
Could you post the
Helper.parseIDateFromString
function? The problem is probably related to timezone... – Christian C. Salvadó Commented Jun 5, 2019 at 18:05 - Sorry, I updated question, – POV Commented Jun 5, 2019 at 18:06
- 2 It's because of your timezone. – Julian W. Commented Jun 5, 2019 at 18:06
- 1 I have personally ran into some silent inaccuracies in JavaScript dates (due to my ignorance i guess). What are your views on dependencies in your project? Would you be against using moment.js? – Arthur Hylton Commented Jun 5, 2019 at 18:17
4 Answers
Reset to default 2You could use a simple regex to format the string using replace:
/(\d{4})-(\d{2})-(\d{2}).+/
// Set the inital date to a UTC date
var date = new Date(new Date().toLocaleString("en-US", {timeZone: "UTC"}))
// Update the day without affecting the month/day when using toISOString()
date.setDate(1)
// Format the date
let formatted = date.toISOString().replace(/(\d{4})-(\d{2})-(\d{2}).+/, '$3-$2-$1')
console.log(formatted)
The default javascript date uses your local timezone, by converting it to something else you can end up with a different date.
You can do it
var firstDay = new Date().toISOString().slice(0, 8) + '01';
console.log(firstDay);
The date object in javascript can be somewhat tricky. When you create a date, it is created in your local timezone, but toISOString() gets the date according to UTC. The following should convert the date to ISO but keep it in your own time zone.
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var day = 0;
if (firstDay.getDate() < 10) {
day = '0' + firstDay.getDate();
}
var month = 0;
if ((firstDay.getMonth() + 1) < 10) {
//months are zero indexed, so we have to add 1
month = '0' + (firstDay.getMonth() + 1);
}
firstDay = firstDay.getFullYear() + '-' + month + '-' + day;
console.log(firstDay);