Does anyone know how to parse a json timespan object? I'd like to return the UTC timespan to my view, and then convert it to the local client time, but I haven't found any reference for how to do that.
I'm using mvc so I've got this model:
public class TimeSpanModel
{
public TimeSpan StartTime { get; set; }
public TimeSpanModel()
{
this.StartTime = DateTime.UtcNow.TimeOfDay;
}
}
and in my controller I return this model to my view like this:
public ActionResult GetTimeSpanInfo()
{
TimeSpanModel tsm= new TimeSpanModel ();
return Json(tsm);
}
I'm making the call like this from the view:
$.ajax({
type: 'POST',
url: '@Url.Content("~/Controller/GetTimeSpanInfo")',
success: function (data) {
alert(data.StartTime);
var dt = new Date(data.StartTime);
alert(dt.toString());
}
});
but in the first alert box, I only see this: [object Object] so I tried to convert the timespan to a Date, but in the second alert box, I get Invalid Date.
Will I have to convert the timespan to a string, and then concatenate that string with some odd date that I don't need in order to create a 'valid' date and then convert it to local time, and then extract the time from that?
Or is there an easier, more elegant way of working with TimeSpans, or just the Time portion of a datetime value?
Thanks for any help.
P.S. It may seem silly to get the UTCnow time only to convert it to local time, but I will eventually get this UTC time value from a db table - type time(0). The method I posted above is merely a shorter way to test how to handle this value once I get it from the db and then set the value in the model.
The [object Object]
that you're seeing is because there isn't a JSON representation for TimeSpan so the easiest solution would be to use a common format to pass this, which is milliseconds.
public ActionResult GetTimeSpanInfo()
{
TimeSpanModel tsm= new TimeSpanModel ();
return Json(tsm.TotalMilliseconds.ToString());
}
and parse in the javascript using the Date constructor Date(milliseconds), as follows follows:
$.ajax({
type: 'POST',
url: '@Url.Content("~/Controller/GetTimeSpanInfo")',
success: function (data) {
alert(data);
var dt = new Date(data);
alert(dt.toString());
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With