.net4.0中json时间转换问题

后端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        public JsonResult Test()
        {
            Person p = new Person();
            p.Name = "zhangsan";
            p.Age = 20;
            p.Created = DateTime.Now;
           return Json(p, JsonRequestBehavior.AllowGet);
        }
    }

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public DateTime Created { get; set; }
    }
}

 

 

前端代码

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>


<input type="button" value="okkkkkk" onclick="s();"/>

<script type="text/javascript">
    function s() {
        $.get("/home/test",{r:Math.random()}, function (res) {
            alert(res.Name);
            alert(res.Created);
            alert(getDate(ConvertJSONDateToJSDateObject(res.Created)));
            alert(getDateTime(ConvertJSONDateToJSDateObject(res.Created)));
        })
    }

    function ConvertJSONDateToJSDateObject(jsondate) {
        var date = new Date(parseInt(jsondate.replace("/Date(", "").replace(")/", ""), 10));
        return date;
    }


    function getDate(date) {
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return year + "-" + month + "-" + day;
    }

    /* 获取日期时间格式*/
    function getDateTime(date) {
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hh = date.getHours();
        var mm = date.getMinutes();
        var ss = date.getSeconds();
        return year + "-" + month + "-" + day + " " + hh + ":" + mm + ":" + ss;
    }
</script>

你可能感兴趣的:(.net)