2

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

ArthurJ
  • 777
  • 1
  • 14
  • 39
  • 1
    if you have `"2021-08-21 00:00:00"` i.e. a string - then replace the space with a T, and append a Z - done if you have a Date object, however, adjust the minutes according to the dates timezone `d.setMinutes(d.getMinutes() - d.getTimezoneOffset())` – Bravo Aug 21 '21 at 08:48
  • @Bravo - updated question to include my date code. – ArthurJ Aug 21 '21 at 08:51
  • The question doesn't make sense. You say you "have" a timestamp in the format YYYY-MM-DD HH:mm:ss, but then go on to say you're generating that format from a Date using moment.js. Then you want to reformat the string so generated. Why not just format it as you want in the first place? I.e. something like `cdt.format('YYYY-MM-DDTHH:mm:ss.SSSZ')`. The '.000' part is decimal seconds, the Z in a format string is a token that means "show the offset as ±HH:mm", as a character in a timestamp it means +0 offset (aka UTC). Which context are you using it in? – RobG Aug 22 '21 at 04:32

2 Answers2

2

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>
sbingner
  • 124
  • 7
0

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());
Bravo
  • 6,022
  • 1
  • 10
  • 15
  • @RobG - yeah, damn the new IE :p I was actually hoping to find out if I even understand the question to be honest - people say I have this date - but don't say if it's a string or a Date or a the output of something or a general concept! :p – Bravo Aug 22 '21 at 02:40