1

Microsoft ASP.NET MVC's JSON serializer converts date time values to something like "\/Date(1239018869048)\/".

I have a component on the client side that uses this format to show a date-time picker. However, create date time values from different sources:

  1. From JSON returned by a controller's action
  2. From some values rendered in a Razor page

The first source creates date times of the required format, that is, "\/Date(1239018869048)\/". However, the second source renders date time in a human-readable format, that is, 7/31/2013 10:03:53 AM.

Is there anyway to create JSON serialized date formats in Razor pages?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Omid Shariati
  • 1,904
  • 5
  • 22
  • 44
  • Possibly you are looking for this, http://stackoverflow.com/questions/668488/parsing-json-datetime-from-newtonsofts-json-serializer – Jatin patil Jul 31 '13 at 06:17

2 Answers2

2

JSON does not define a date format. However, the date format used by your client side component is most likely the number of milliseconds elapsed since 01 January 1970 00:00:00. To produce the expected output you need to compute the number of milliseconds elapsed and you can do it like this (assuming dateTime contains the date you want to convert):

var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var elapsedSinceEpoch = dateTime - epoch;
var formattedDateTime = string.Format(
  @"""\/Date({0:F0})\/""",
  elapsedSinceEpoch.TotalMilliseconds
);

To use this formatting in a Razor view it is probably best to wrap the code in a helper method.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
0

You need to choose a single date format that is standard and have a javascript library that essentially just takes the various date formats and spits out your preferred format. E.g. This would be relevant in the case where you need to use jQuery UI's datepicker but then pass the selected date back in a different format.

There are several date handling libraries available but I use MomentJS. This can accept the /Date(...)/ format and return a date object, but you can also create date objects from specific string formats. You can also use it to pump out a date in a custom string format:

var formattedDate = moment().format("[/Date(]X[)/]");
Digbyswift
  • 10,310
  • 4
  • 38
  • 66
  • Unless I have misinterpreted the question it is about how to format a date in a specific JSON format on the server side. – Martin Liversage Jul 31 '13 at 08:26
  • Hmm, I read it the other way because he has a client-side date-picker that creates a different date format. Well, we have both angles covered then :) – Digbyswift Jul 31 '13 at 08:29