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";
}
2
  • Please read the docs. What have you tried? Commented May 20, 2018 at 16:29
  • I read the docs, try all methods from "Conversion getter" part, but with no success. Commented May 20, 2018 at 16:34

2 Answers 2

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())
Sign up to request clarification or add additional context in comments.

1 Comment

It works, but is there a way to do it with plain JavaScript ?
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!

2 Comments

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".
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.