0

I'm trying to convert something like this 2020-10-01T17:00:00.000Z to the correct time something like 06:00:00 PM. Pls see my code below:

const date = "2020-10-01T17:00:00.000Z";
const output = new Date(date).toLocaleTimeString('en-US');
console.log(output);
Joseph
  • 7,042
  • 23
  • 83
  • 181
  • If you're in a time zone which is one hour ahead of UTC, and in a locale that formats its times with two digit hours, that is exactly what that code will show. – Heretic Monkey Oct 02 '20 at 15:54
  • Does this answer your question? [How to format a JavaScript date](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date) – Heretic Monkey Oct 02 '20 at 15:55
  • Otherwise, look at the top answers to the question linked and see the options available. – Heretic Monkey Oct 02 '20 at 15:56
  • @HereticMonkey. I wanted to output like 05:00:00 PM. How would i do that? Thank you – Joseph Oct 02 '20 at 15:58
  • You would research. First by looking at [the documentation for `toLocaleTimeString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString#Using_options). Then searching [Stack Overflow](https://stackoverflow.com/search?q=How+to+format+time+in+JavaScript+in+the+format+HH%3AMM%3ASS%3F). – Heretic Monkey Oct 02 '20 at 16:39

1 Answers1

1

If you specifically need the time to be in UTC (instead of the local user's timezone), then I think you would need to build your own formatter function to do it, e.g.:

function formatDate(str, includeDate){
  const date = new Date(str);
  const hours = date.getUTCHours();
  
  let twoDigits = (no) => {
    const str = no.toString();
    return (str.length === 1 ? '0' + str : str);
  };
  
  let strdate = (includeDate ? twoDigits(date.getUTCMonth() + 1) + '/' + twoDigits(date.getUTCDate()) + '/' + twoDigits(date.getUTCFullYear()) + ' ' : '');
  
  if(12 <= hours) {
    return strdate + twoDigits(hours === 12 ? 12 : hours - 12) + ':' + twoDigits(date.getUTCMinutes()) + ':' + twoDigits(date.getUTCSeconds()) + ' PM';
  } else {
    return strdate + twoDigits(hours) + ':' + twoDigits(date.getUTCMinutes()) + ':' + twoDigits(date.getUTCSeconds()) + ' AM';
  };
};

console.log(formatDate("2020-10-01T17:00:00.000Z", true));

Here, you are constructing the time string from individual UTC segments. You could alternatively parse the input string using a regex, get the number of hours and then build the string that way.

Edit: updated to optionally also include the date, in US format mm/dd/yyyy.

sbgib
  • 5,580
  • 3
  • 19
  • 26