0

Please don't make duplicate vs ASP.NET Parse DateTime result from ajax call to javascript date and Parsing DateTime format passed from Ajax to “dd/MM/yyyy”, I have been read carefully. But my question is differences.

I have data from asp.net load by ajax below.

 Datetime in c#: "2019-05-04" The result in ajax is: "/Date(1556895600000+0900)/" 

You can see the result automatic add time UTC offset to DateTime, I don't know why.

How can I convert to DateTime in javascript vs data above?

var d = new Date(("/Date(1556895600000+0900)/").match(/\d+/)[0] * 1) console.log(d)

You can see: Result "2019-05-03T15:00:00.000Z", But I expect result "2019-05-04". How can I do this?

4
  • That's an invalid date value. Do you have access to the C# code? Commented May 9, 2019 at 10:28
  • Otherwise, you're going to need to add 9 hours to d to get the correct value. Commented May 9, 2019 at 10:31
  • @ Heretic Monkey: public DateTime TheDate { get; set; }, My sytem publish for Korea, and Vietnam, China, Japan. But in Korea add 9, Vietnam add 7...=> This is not good solution. Commented May 9, 2019 at 10:35
  • You can set up C# to output whatever date format you want, including ISO 8601 in UTC, which you can pass directly to new Date() without a lot of this parsing work. Commented May 9, 2019 at 10:52

1 Answer 1

2

Look I'm no dates expert but the following looks convincing to me

const parse = str => { let [_, timestamp, offsetHours, offsetMinutes] = str.match(/(\d+)([+-]\d\d)(\d\d)/).map(Number); let date = new Date(timestamp); date.setHours(date.getHours() + offsetHours); date.setMinutes(date.getMinutes() + offsetMinutes); return date; } console.log( parse("/Date(1556895600000+0900)/") .toJSON() ) console.log( parse("/Date(1556895600000-0700)/") .toJSON() )

Here's a ES3 version in case it doesn't work in older browsers (as the OP said in the comments)

function parse(str) { var matches = str.match(/(\d+)([+-]\d\d)(\d\d)/).map(Number); var timestamp = matches[1]; var offsetHours = matches[2]; var offsetMinutes = matches[3]; var date = new Date(timestamp); date.setHours(date.getHours() + offsetHours); date.setMinutes(date.getMinutes() + offsetMinutes); return date; } console.log( parse("/Date(1556895600000+0900)/") .toJSON() ) console.log( parse("/Date(1556895600000-0700)/") .toJSON() )

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

2 Comments

Thank Devansh J. But it only work on Chrome. How can you fix it on IE?
Sorry again. How can work with timeofset <0 for example: /Date(1556895600000-0700)?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.