2

I need to display a date formatted as a UTC date, and I should do this with Datejs. Is this possible?

I need to do something like

var d = new Date();
var dateString = d.toString("d \n MMM/yyyy \n H:mm:ss");

...but with date and time formatted as UTC.

I looked at the docs but the closest thing I found is

d.toISOString();

which gives me a date as a UTC string but not in the format I want.

edit: changed toUTCSTring to toISOString

cdarwin
  • 4,141
  • 9
  • 42
  • 66
  • UTC is not a format, it's a time standard. – RobG May 10 '19 at 05:07
  • There are already [many questions on formatting dates](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date), surely one of those answers your question. – RobG May 10 '19 at 05:19

1 Answers1

0

Consider using Moment.js, a more well-maintained library for working with dates and times.

moment.utc(d).format("D [\n] MMM/YYYY [\n] H:mm:ss");

If this is not an option, you can shift the date by the timezone offset (which gives you the date/time portion of the UTC date but in the local timezone), then format it:

var d2 = new Date(d.getTime() + d.getTimezoneOffset() * 60 * 1000);
console.log(d2.toString("d \n MMM/yyyy \n H:mm:ss"));

Edit: Removed dependency on built-in date parser.

Boatmarker
  • 197
  • 1
  • 10
  • 1
    The OP is about Date.js, so your answer should be based on Date.js. – RobG May 10 '19 at 05:08
  • @RobG The second part of my answer is based on Date.js. I don't think it's wrong to also suggest possibly better alternatives. – Boatmarker May 10 '19 at 12:19
  • Fair enough, but the second part of your answer assumes the built–in parser will correctly parse the string. At least one current browser doesn't parse it correctly, which one reason why it's recommended not to use it. If the OP wants to shift the date to UTC, there are already many answers for that. – RobG May 10 '19 at 12:38
  • @RobG Noted, after some testing, I found that this does in fact fail in Safari. Edited my answer to remove this dependency. Out of curiosity, do you know of a way to test code JSFiddle-style, but across multiple browsers? – Boatmarker May 11 '19 at 03:51