1

I have a DateTime in c # code that I'm trying to convert it in a string before sending it to the front end.

For example, I have this C#:

 DateTime utcN = DateTime.UtcNow;
 string utcNow =  utcN.ToString(); //an example "12/31/2099 12:00:00 AM"

And in the front end javascript I convert this to date as:

var date = new Date(Date.parse(utcNow));

Some users are complaining about NaN values, but since I can't debug it is difficult to understand why this is happening!

4
  • What format does ToString() produce? Are your users in different Cultures than the server? Can you give us a minimal reproducible example? Commented Nov 17, 2022 at 15:55
  • 1
    You probably need to format it to ISO (.ToString("o")) Commented Nov 17, 2022 at 15:56
  • @gunr2171 added the format in the description Commented Nov 17, 2022 at 16:08
  • The use of Date.parse is redundant. new Date(Date.parse(utcNow)) will produce exactly the same result as new Date(utcNow). Commented Nov 17, 2022 at 20:55

1 Answer 1

1

DateTime.ToString() produces string which depends on current culture. Such string is only suitable for presenting to user in UI, it is NOT suitable for data transfer.

Always use stable format for transferring dates as strings, which does not depend on culture settings. In this particular case, note that documentation of javascript Date.parse says:

Only the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.

So, use ISO 8601 format:

DateTime utcN = DateTime.UtcNow;
string utcNow =  utcN.ToString("O");
Sign up to request clarification or add additional context in comments.

3 Comments

Will try out and will let the user test it. Thanks!
If you're displaying on the UI, I would recommend moment.js which does wonders with ISO strings.
"Only the ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ) is explicitly specified to be supported." is wrong. There are three supported formats as documented ECMA-262:Date.parse. MDN is a useful resource but it is not normative.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.