0

How can I convert "2011-09-30T00:00:00" date time string to UTC date in JavaScript?

I tried new Date("2011-09-30T00:00:00") but it converts to "2011-09-29T23:00:00.000Z".

developer
  • 1,401
  • 4
  • 28
  • 73
  • `new Date("2011-09-30T00:00:00")` should not convert it to `"2011-09-29T23:00:00.000Z"`, that happens only if you do `new Date("2011-09-30T00:00:00").toISOString()`. Where are you trying this? Have you tried `new Date("2011-09-30T00:00:00").toUTCString()`? – M3rr1 Sep 30 '21 at 19:14
  • Thanks for your comment, I tried toUTCString but I need a date object while toUTCString returns a string. Would new Date( new Date("2011-09-30T00:00:00").toUTCString()) return a UTC date? – developer Sep 30 '21 at 21:25

2 Answers2

1
function createDateAsUTC(dateYmd) {
    var dateYmdSplited = dateYmd.split('-');
    var y = Number(dateYmdSplited[0]);
    var m = Number(dateYmdSplited[1]) - 1;
    var d = Number(dateYmdSplited[2])

    return new Date(Date.UTC(y, m, d, 0, 0, 0))
}

var fecha = "2021-09-01";
var d = createDateAsUTC(fecha);
1

Simple:

function createDateUTC(dateUTC) {
    return new Date(dateUTC + "Z");
}

var dateUTC = createDateUTC("2011-09-30T00:00:00");

console.log(dateUTC);
Killer
  • 188
  • 3
  • 14
  • 1
    Interesting! - So does adding a "Z" makes it a UTC date? – developer Sep 30 '21 at 21:33
  • 2
    A good answer should explain why the OP has their issue and how your code fixes it. – RobG Oct 01 '21 at 08:52
  • 1
    @developer—see [*What are valid Date Time Strings in JavaScript?*](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript) and [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Oct 01 '21 at 08:53
  • 1
    Sorry for the delay but @RobG already quoted some good topics about the reason why the code worked and why the issue happened. – Killer Oct 05 '21 at 14:26