Search code examples
javascriptdatedatejs

Formatting a date as a UTC date with Datejs


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


Solution

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