Dragan Menoski
Dragan Menoski

Reputation: 1102

Convert JavaScript Date to formatted String

I have a JavaScript Date object and want to convert it into String like this: 2018-05-24T11:00:00+02:00

var dateObj = new Date("Thu May 24 2018 11:00:00 GMT+0200");

function convertToString(dateObj) {
    // converting ...
    return "2018-05-24T11:00:00+02:00";
}

Upvotes: 0

Views: 862

Answers (2)

ful-stackz
ful-stackz

Reputation: 332

You have quite the options to represent the DateTime object as a string. This question was already elaborated on in the following StackOverflow answers:

Personally, I would sacrifice a few extra lines in my document for the Vanilla JavaScript variant. This way I would have complete control of the format and of the function responsible for the formatting - easier debugging and future changes. In your case that would be (using string literals to shorten the code):

var date = new Date("Thu May 24 2018 11:00:00 GMT+0200");

function convertToString(date) {
  return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}-...`;
}

And so on. On this page Date - JavaScript | MDN, in the left you have all the methods that extract some kind of information from the Date object. Use them as you wish and you can achieve any format you desire. Good luck!

Upvotes: 1

alfredopacino
alfredopacino

Reputation: 3241

You can use moment.js, it handles pretty much all the needs about date formatting you may have.

var dateObj = new Date("Thu May 24 2018 11:00:00 GMT+0200");
console.log(moment(dateObj).format())

Upvotes: 1

Related Questions