My application is getting a datetime value from JSON in the following
format:
Created "/Date(1335232596000)/"
Instead of using a DateTime
property on your view model that is serialized by the JavaScriptSerializer
using the aformentioned format, use a string property and do the formatting on the server => use a real view model.
Here's how you could format this DateTime
DateTime date = ...
string created = date.ToString("MM/dd/yyyy hh:mm:sstt ") + GetTimeZoneName(date);
// pass the created string to the view
where TimeZoneName
is defined like this:
public static string GetTimeZoneName(DateTime date)
{
var name = TimeZone.CurrentTimeZone.IsDaylightSavingTime(date)
? TimeZone.CurrentTimeZone.DaylightName
: TimeZone.CurrentTimeZone.StandardName;
var newName = "";
var parts = name.Split(' ');
foreach (var s in parts)
{
if (s.Length >= 1)
{
newName += s.Substring(0, 1);
}
}
return newName;
}
Now inside your view you will receive the date formatted as it has to be formatted. And if for some reason you also needed this date under the form of a javascript Date
object inside the view you could also leave the DateTime property on the view model and the serializer will include both.