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".

2
  • 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()? Commented Sep 30, 2021 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? Commented Sep 30, 2021 at 21:25

2 Answers 2

1

Simple:

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

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

console.log(dateUTC);

Sign up to request clarification or add additional context in comments.

4 Comments

Interesting! - So does adding a "Z" makes it a UTC date?
A good answer should explain why the OP has their issue and how your code fixes it.
Sorry for the delay but @RobG already quoted some good topics about the reason why the code worked and why the issue happened.
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.