0

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";
}
Dragan Menoski
  • 1,092
  • 14
  • 33

2 Answers2

1

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())
alfredopacino
  • 2,979
  • 9
  • 42
  • 68
1

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!

ful-stackz
  • 302
  • 4
  • 10
  • Thank you for your extensive response. The first link (toLocaleDateString()) doesn't solve the problem. The second link use the external library, so it's not what I want. The third link show how can I make a format that is entirely up to me, but it doesn't show how I can get the timezone offset from date object as "+02:00". As I mention I see the MDN docs and the getTimezoneOffset() method give me the "-120" as result, but I need "+02:00". – Dragan Menoski May 20 '18 at 17:05
  • `date.getTimezoneOffset()` returns the time offset in minutes. In your case the output is completely correct `-120 / -60 = +2`. If you scroll down in the MDN page of `getTimezoneOffset()`, section **Description**, they show some examples. One of the examples is that if you are at **UTC+3** the function will return `-180` (180 minutes = 3 hours). – ful-stackz May 20 '18 at 17:13