0

I am working on project uses angular4(frontend) and java(backend). I get the date in below format from java backend server into angular server.

2018-05-23T18:30:00.000+0000

I need to convert it into javascript/angular Date object. I have tried below code

Date d = new Date(java_date);

but this gives Invalid Date error.

Any idea how to deal with above date format.

5
  • That string is definitely a valid date, so the variable java_date must have some other string (or something else) in it. Commented Sep 29, 2018 at 12:49
  • 1
    Make sure you passing the date as "2018-05-23T18:30:00.000+0000" ,i.e., as string Commented Sep 29, 2018 at 12:51
  • 1
    Also it should be let d = new Date(str) not Date d. Commented Sep 29, 2018 at 12:59
  • That Java backend should be changed to return the result of Instant.now().toString() to get a standard Z on the end rather than +0000. Commented Sep 29, 2018 at 15:51
  • Related: What are valid Date Time Strings in JavaScript? Commented Sep 29, 2018 at 18:44

2 Answers 2

2

The string "2018-05-23T18:30:00.000+0000" is not consistent with the format in ECMA-262, it's missing colon in the timezone offset between the hours and minutes, so implementations may treat it as invalid (e.g. Safari).

You have a number of options:

  1. Replace the timezone offset with "Z" and use the built–in parser: new Date('2018-05-23T18:30:00.000Z')
  2. Insert a colon in the offset and use the built–in parser: new Date('2018-05-23T18:30:00.000+00:00')
  3. Write your own parser for this particular format (maybe 4 lines of code)
  4. Use a library (there are many good ones and they can help with formatting too)

I'd recommend either 3 or 4 as the built–in parser is notoriously fickle, but any of the above will likely do.

Sign up to request clarification or add additional context in comments.

Comments

0

The Date as you wrote it - given by its ISO string, you should parse it using JS/Angular

var a = Date.parse("2018-05-23T18:30:00.000+0000");

Here's a relevant link to MDN :

MDN Parse

MDN ISO

7 Comments

I face issue due to last +0000 if I removed it then everything works perfect, but I don't want to parse it using string manipulation.
Date constructor (when passed a string) calls Date.parse. You answer does not solve anything.
@PrasadParab What browser are you using? Seems to work fine in Chrome
@user184994 correct it works in Chrome but I have tried it on Safari12.0 there its not working😨
In that case, sounds like you have no choice but to manipulate the string value (maybe something like java_date.substring(0, 23))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.