-1

I have tried searching SO but couldn't find any answers replicating what I am trying to achieve...

If I console log the following:

console.log(new Date().getMonth())

It outputs 10.

What I want to do, is take the following date string:

"2020-11-30T08:37:20.717Z"

And convert it so that it's just '10' to indicate the month, like the Date object above, and not the full date string. In that string, the number is '11', so I can't just pull that out unless I minus 1 from it perhaps?

Obviously in December, the output of the console log above would be 11... But I'd want that date string to remain as 10 to indicate November.

But how do I do this? I've seen other examples where they convert it into a month name, but I just wish for it to be the same as the Date object.

Any pointers would be great - hope that's clear.

Jon Nicholson
  • 927
  • 1
  • 8
  • 29

2 Answers2

1

Yes, you need to subtract

It is safer than creating a date object since the timezone might move the month to the month before or after

const dString = "2020-10-31T23:00:00.000Z"
const mmFromString = dString.match(/-(\d{2})-/)[1]
console.log(mmFromString-1); // 9 (JS October) in any timezone

const d = new Date(dString)
const mmFromDate = d.getMonth();
console.log(mmFromDate) // 10 (JS November) in my timezone
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You can construct a Date object from the string and call getMonth().

console.log(new Date("2020-11-30T08:37:20.717Z").getMonth());
Unmitigated
  • 76,500
  • 11
  • 62
  • 80