Converting a date time to UTC but keeping the same date and time components

Viewed 869

New to JavaScript dates and format and also using moment.js but I have the following date/time:

"2021-08-21 00:00:00"

but need to convert it to be this same date/time using moment.js, but in this format:

"2021-08-21T00:00:00.000Z"

To achieve the top date, I am using the following code:

let value = "00:00:00";
let cdt = moment(value, 'HH:mm:ss');
console.log(cdt.format('YYYY-MM-DD HH:mm:ss'))

Unsure what the .000Z are at the end but can someone pls assist with conversion but keeping to same date and time as first date/time

2 Answers

This is answered by How do I format a date as ISO 8601 in moment.js?

TLDR; you want moment().toISOString();

EDIT: Since you added your code, you'd probably want:

let value = "00:00:00";
let cdt = moment.utc(value, 'HH:mm:ss');
console.log(cdt.toISOString())
<script src="https://momentjs.com/downloads/moment.min.js"></script>

If I understand what you want ... no need for the no longer updated moment.js library

const dateString = "2021-08-21 00:00:00"

const asLocal = dateString.replace(" ", 'T');

const asUTC = asLocal + 'Z';

console.log(new Date(asLocal).toString());
console.log(new Date(asUTC).toUTCString());

Related