如何使用json和javascript/jquery正确处理db时间值

cod*_*bie 5 json timespan

有谁知道如何解析json timespan对象?我想将UTC时间跨度返回到我的视图,然后将其转换为本地客户端时间,但我没有找到任何有关如何执行此操作的参考.

我正在使用mvc所以我有这个型号:

public class TimeSpanModel
{
    public TimeSpan StartTime { get; set; }

    public TimeSpanModel()
    {
        this.StartTime = DateTime.UtcNow.TimeOfDay;

    }
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我将此模型返回到我的视图中,如下所示:

public ActionResult GetTimeSpanInfo()
    {
        TimeSpanModel tsm= new TimeSpanModel ();
        return Json(tsm);
    }
Run Code Online (Sandbox Code Playgroud)

我从视图中这样打电话:

$.ajax({
        type: 'POST',
        url: '@Url.Content("~/Controller/GetTimeSpanInfo")',
        success: function (data) {
        alert(data.StartTime);
        var dt = new Date(data.StartTime);
        alert(dt.toString());
        }
    });
Run Code Online (Sandbox Code Playgroud)

但在第一个警告框中,我只看到这个:[object Object]所以我试图将时间跨度转换为Date,但是在第二个警告框中,我得到了无效日期.

我是否必须将时间跨度转换为字符串,然后将该字符串与我不需要的奇怪日期连接起来以创建"有效"日期然后将其转换为本地时间,然后从中提取时间?

或者是使用TimeSpans更简单,更优雅的方式,还是只是日期时间值的时间部分?

谢谢你的帮助.

PS获取UTCnow时间仅将其转换为本地时间似乎很愚蠢,但我最终将从db表中获取此UTC时间值 - 键入时间(0).我上面发布的方法只是一种较短的方法来测试如何从db中获取该值然后在模型中设置值.

Ric*_*son 2

您看到的[object Object]是因为 TimeSpan 没有 JSON 表示形式,所以最简单的解决方案是使用通用格式来传递它,即毫秒。

public ActionResult GetTimeSpanInfo()
    {
        TimeSpanModel tsm= new TimeSpanModel ();
        return Json(tsm.TotalMilliseconds.ToString());
    }
Run Code Online (Sandbox Code Playgroud)

并在 javascript 中使用 Date 构造函数 Date(毫秒) 进行解析,如下所示:

$.ajax({
        type: 'POST',
        url: '@Url.Content("~/Controller/GetTimeSpanInfo")',
        success: function (data) {
        alert(data);
        var dt = new Date(data);
        alert(dt.toString());
        }
    });
Run Code Online (Sandbox Code Playgroud)