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!

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
Ser
  • 13
  • 3

1 Answers1

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");
Evk
  • 98,527
  • 8
  • 141
  • 191
  • Will try out and will let the user test it. Thanks! – Ser Nov 17 '22 at 16:37
  • If you're displaying on the UI, I would recommend moment.js which does wonders with ISO strings. – GH DevOps Nov 17 '22 at 16:45
  • "*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*](https://262.ecma-international.org/#sec-date.parse). MDN is a useful resource but it is not normative. – RobG Nov 17 '22 at 20:53