Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/446.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ASP.NET MVC JsonResult日期格式_Javascript_Asp.net Mvc_Json - Fatal编程技术网

Javascript ASP.NET MVC JsonResult日期格式

Javascript ASP.NET MVC JsonResult日期格式,javascript,asp.net-mvc,json,Javascript,Asp.net Mvc,Json,我有一个控制器操作,它有效地简单地返回模型的JsonResult。因此,在我的方法中,我有如下内容: return new JsonResult(myModel); 除了一个问题外,这很有效。模型中有一个date属性,它似乎在Json结果中返回,如下所示: "\/Date(1239018869048)\/" 我应该如何处理日期,以便以我要求的格式返回它们?或者如何在脚本中处理上述格式?请参阅此线程: 基本上,虽然Date()格式是有效的javascript,但它不是有效的JSON(这是有区

我有一个控制器操作,它有效地简单地返回模型的JsonResult。因此,在我的方法中,我有如下内容:

return new JsonResult(myModel);
除了一个问题外,这很有效。模型中有一个date属性,它似乎在Json结果中返回,如下所示:

"\/Date(1239018869048)\/"
我应该如何处理日期,以便以我要求的格式返回它们?或者如何在脚本中处理上述格式?

请参阅此线程:

基本上,虽然
Date()
格式是有效的javascript,但它不是有效的JSON(这是有区别的)。如果您想要旧的格式,您可能需要自己创建一个facade并转换值,或者找到一种方法在
JsonResult
中找到您的类型的序列化程序,并让它使用日期的自定义格式。

只需展开即可

不考虑日期值。MS必须进行调用,他们选择的路径是利用字符串javascript表示中的一个小技巧:字符串文本“/”与“\/”相同,字符串文本永远不会序列化为“\/”(甚至“\/”必须映射为“\\/”)

请参阅以获得更好的解释(向下滚动至“从JavaScript文本到JSON”)

JSON的痛处之一是 缺少日期/时间文字。许多的 人们感到惊讶和失望 当他们第一次 遇到JSON。简单的解释 (安慰还是不安慰)因为没有 日期/时间文本就是JavaScript 也从来没有一个:支持 JavaScript中的日期和时间值是 全部提供到日期 对象大多数应用程序使用JSON 因此,作为一种数据格式 倾向于使用字符串或字符串 表示日期和时间的数字 价值观如果使用了字符串,则可以 一般认为它在ISO中 8601格式。如果使用了数字, 相反,该值通常为 被认为是指 通用坐标系中的毫秒数 自epoch起的时间(UTC),其中epoch为 定义为1970年1月1日午夜 (UTC)。再说一次,这仅仅是一个问题 约定,而不是JSON的一部分 标准如果您正在交换数据 使用另一个应用程序,您将 需要检查其文档以查看 它如何编码日期和时间值 在JSON文本中。例如 微软的ASP.NET AJAX既不使用这两种技术,也不使用这两种技术 所述公约的一部分。相当地 它将.NET日期时间值编码为 JSON字符串,其中 字符串为/Date(ticks)/和where 刻度表示自 纪元(UTC)。1989年11月29日, 上午4:55:30,UTC编码为 “\/日期(628318530718)\/”

一个解决方案是将其解析出来:

value = new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10));
但是,我听说在某个地方有一个设置,可以让序列化程序使用
newdate(xxx)
语法输出
DateTime
对象。我会试着把它挖出来


JSON.parse()
的第二个参数接受一个
revivier
函数,其中规定了值最初是如何生成的,然后返回

以下是日期的示例:

var parsed = JSON.parse(data, function(key, value) {
  if (typeof value === 'string') {
    var d = /\/Date\((\d*)\)\//.exec(value);
    return (d) ? new Date(+d[1]) : value;
  }
  return value;
});

请参阅

的文档这里是我的Javascript解决方案-与JPot非常相似,但更短(可能更快一点):

“value.substr(6)”去掉“/Date”()部分,parseInt函数忽略结尾出现的非数字字符

编辑:我故意省略了基数(parseInt的第二个参数);请参见。另外,请注意,ISO-8601日期比旧格式更受欢迎——因此新开发通常不应使用这种格式

对于ISO-8601格式的JSON日期,只需将字符串传递到日期构造函数:

var date = new Date(jsonDate); //no ugly parsing needed; full timezone support

这不是最优雅的方式,但对我来说很有效:

var ms = date.substring(6, date.length - 2);
var newDate = formatDate(ms);


function formatDate(ms) {

    var date = new Date(parseInt(ms));
    var hour = date.getHours();
    var mins = date.getMinutes() + '';
    var time = "AM";

    // find time 
    if (hour >= 12) {
        time = "PM";
    }
    // fix hours format
    if (hour > 12) {
        hour -= 12;
    }
    else if (hour == 0) {
        hour = 12;
    }
    // fix minutes format
    if (mins.length == 1) {
        mins = "0" + mins;
    }
    // return formatted date time string
    return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear() + " " + hour + ":" + mins + " " + time;
}

我也遇到了同样的问题,我没有返回实际的日期值,而是使用了字符串(“dd-MMM-yyyy”),然后在javascript中使用了新的日期(datevalue),其中datevalue可能是“2009年1月1日”.

我一直在研究这个问题的解决方案,因为上面的答案对我都没有帮助。我正在使用jquery周日历,需要我的日期在服务器上和页面上本地显示时区信息。经过一番深入研究,我找到了一个可能对其他人有所帮助的解决方案

我使用的是asp.net 3.5、vs 2008、asp.net MVC 2和jquery周日历

首先,我使用的是Steven Levithan编写的库,它帮助处理客户端的日期。isoUtcDateTime格式非常适合我的需要。在我的jquery AJAX调用中,我使用带有isoUtcDateTime格式的库提供的format函数,当AJAX调用命中我的操作方法时,就会设置日期时间类型到本地,并反映服务器时间

当我通过AJAX将日期发送到我的页面时,我通过使用“ddd,dd-MMM-yyyy-HH':“mm':“ss”GMT“zzzz”格式化日期,将它们作为文本字符串发送。这种格式在客户端使用

var myDate = new Date(myReceivedDate);
以下是我的完整解决方案减去Steve Levithan的源代码,您可以下载:

控制器:

public class HomeController : Controller
{
    public const string DATE_FORMAT = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

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


    public JsonResult GetData()
    {
        DateTime myDate = DateTime.Now.ToLocalTime();

        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }

    public JsonResult ReceiveData(DateTime myDate)
    {
        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }
}
Javascript:

<script type="text/javascript">

function getData() {
    $.ajax({
        url: "/Home/GetData",
        type: "POST",
        cache: "false",
        dataType: "json",
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
            sendData(newDate);
        }
    });
} 

function cleanDate(d) {
    if (typeof d == 'string') {
        return new Date(d) || Date.parse(d) || new Date(parseInt(d));
    }
    if (typeof d == 'number') {
        return new Date(d);
    }
    return d;
}

function sendData(newDate) {
    $.ajax({
        url: "/Home/ReceiveData",
        type: "POST",
        cache: "false",
        dataType: "json",
        data:
        {
            myDate: newDate.format("isoUtcDateTime")
        },
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
        }
    });
}

// bind myButton click event to call getData
$(document).ready(function() {
    $('input#myButton').bind('click', getData);
});
</script>

函数getData(){
$.ajax({
url:“/Home/GetData”,
类型:“POST”,
缓存:“false”,
数据类型:“json”,
成功:功能(数据){
警报(data.myDate);
var newDate=cleanDate(data.myDate);
警报(新日期);
sendData(newDate);
}
});
} 
函数清除日期(d){
if(typeof d=='string'){
返回新日期(d)| | Date.parse(d)| |新日期(parseInt(d));
}
如果(类型d=='number'){
返回新日期(d);
}
返回d;
}
函数sendData(newDate){
$.ajax({
url:“/Home/ReceiveData”,
类型:“POST”,
缓存:“false”,
数据类型:“json”,
数据:
{
myDate:newDate.format(“isoUtcDateTime”)
},
成功:功能(数据){
警报(data.myDate);
<script type="text/javascript">

function getData() {
    $.ajax({
        url: "/Home/GetData",
        type: "POST",
        cache: "false",
        dataType: "json",
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
            sendData(newDate);
        }
    });
} 

function cleanDate(d) {
    if (typeof d == 'string') {
        return new Date(d) || Date.parse(d) || new Date(parseInt(d));
    }
    if (typeof d == 'number') {
        return new Date(d);
    }
    return d;
}

function sendData(newDate) {
    $.ajax({
        url: "/Home/ReceiveData",
        type: "POST",
        cache: "false",
        dataType: "json",
        data:
        {
            myDate: newDate.format("isoUtcDateTime")
        },
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
        }
    });
}

// bind myButton click event to call getData
$(document).ready(function() {
    $('input#myButton').bind('click', getData);
});
</script>
var _myModel = from _m in model.ModelSearch(word)
    select new { date = ((DateTime)_m.Date).ToShortDateString() };
var _test = from _t in adc.ItemSearchTest(word)
                        where _t.Date != null
                        select new { date = ((DateTime)_t.Date).ToShortDateString() };
var _testA = from _t in adc.ItemSearchTest(word)
                         select _i;

            foreach (var detail in _testA)
            {
                if (detail.Date== null)
                {
                    detail.Date= Convert.ToDateTime("1/1/0001");
                }
            }
public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            // Use your custom JavaScriptConverter subclass here.
            serializer.RegisterConverters(new JavascriptConverter[] { new CustomConverter });

            response.Write(serializer.Serialize(Data));
        }
    }
}
public class CustomJsonResult : JsonResult
{
    private const string _dateFormat = "yyyy-MM-dd HH:mm:ss";

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        if (!String.IsNullOrEmpty(ContentType))
        {
            response.ContentType = ContentType;
        }
        else
        {
            response.ContentType = "application/json";
        }
        if (ContentEncoding != null)
        {
            response.ContentEncoding = ContentEncoding;
        }
        if (Data != null)
        {
            // Using Json.NET serializer
            var isoConvert = new IsoDateTimeConverter();
            isoConvert.DateTimeFormat = _dateFormat;
            response.Write(JsonConvert.SerializeObject(Data, isoConvert));
        }
    }
}
[HttpGet]
public ActionResult Index() {
    return new CustomJsonResult { Data = new { users=db.Users.ToList(); } };
}
function JsonDateFormate(dateFormate, jsonDateTime) {
    return $.datepicker.formatDate(dateFormate, eval('new ' + jsonDateTime.slice(1, -1)));
};
function jsonDateFormat(jsonDate) {
  // Changed data format;
  return (new Date(parseInt(jsonDate.substr(6)))).format("mm-dd-yyyy / h:MM tt");
};
var setDate = function(id, d) {
  if (d !== undefined && d !== null) {
    var date = new Date(parseInt(d.replace("/Date(", "").replace(")/", ""), 10));
    var day = ('0' + date.getDate()).slice(-2);
    var month = ('0' + (date.getMonth() + 1)).slice(-2);
    var parsedDate = date.getFullYear() + "-" + (month) + "-" + (day);
    $(id).val(parsedDate);
  }
};
setDate('#productCommissionStartDate', data.commissionStartDate);
String.prototype.jsonToDate = function(){
    try{
        var date;
        eval(("date = new " + this).replace(/\//g,''));
        return date;
    } 
    catch(e){
        return new Date(0);
    }
};
var query = from t in db.Table select new { t.DateField };
var result = from c in query.AsEnumerable() select new { c.DateField.toString("dd MMM yyy") };
function jsonToDate(date,format) {
   return moment(date).format(format);
}
var formattedDate = jsonToDate(date,'MM/DD/YYYY')
function ToJavaScriptDate(value) {
  var pattern = /Date\(([^)]+)\)/;
  var results = pattern.exec(value);
  var dt = new Date(parseFloat(results[1]));
  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}
public class TransactionsViewModel
{
    public string DateInitiated { get; set; }
    public string DateCompleted { get; set; }
}
public class Transaction{
   public DateTime? DateInitiated {get; set;}
   public DateTime? DateCompleted {get; set;}
}
public JsonResult GetTransactions(){

var transactions = _transactionsRepository.All;
        var model = new List<TransactionsViewModel>();

        foreach (var transaction in transactions)
        {
            var item = new TransactionsViewModel
            {
                ...............
                DateInitiated = transaction.DateInitiated.ToString(),
                DateCompleted = transaction.DateCompleted.ToString(),
            };

            model.Add(item);
        }
        return Json(model, JsonRequestBehavior.AllowGet);
}
public class JsonNetFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is JsonResult == false)
        {
            return;
        }

        filterContext.Result = new JsonNetResult(
            (JsonResult)filterContext.Result);
    }

    private class JsonNetResult : JsonResult
    {
        public JsonNetResult(JsonResult jsonResult)
        {
            this.ContentEncoding = jsonResult.ContentEncoding;
            this.ContentType = jsonResult.ContentType;
            this.Data = jsonResult.Data;
            this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
            this.MaxJsonLength = jsonResult.MaxJsonLength;
            this.RecursionLimit = jsonResult.RecursionLimit;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var isMethodGet = string.Equals(
                context.HttpContext.Request.HttpMethod, 
                "GET", 
                StringComparison.OrdinalIgnoreCase);

            if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
                && isMethodGet)
            {
                throw new InvalidOperationException(
                    "GET not allowed! Change JsonRequestBehavior to AllowGet.");
            }

            var response = context.HttpContext.Response;

            response.ContentType = string.IsNullOrEmpty(this.ContentType) 
                ? "application/json" 
                : this.ContentType;

            if (this.ContentEncoding != null)
            {
                response.ContentEncoding = this.ContentEncoding;
            }

            if (this.Data != null)
            {
                response.Write(JsonConvert.SerializeObject(this.Data));
            }
        }
    }
}
[JsonNetFilter]
public ActionResult GetJson()
{
    return Json(new { hello = new Date(2015, 03, 09) }, JsonRequestBehavior.AllowGet)
}
{"hello":"2015-03-09T00:00:00+00:00"}
// ...
filters.Add(new JsonNetFilterAttribute());
using System.Collections.Generic;
using System.Web.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;

namespace Website
{
    /// <summary>
    /// This is like MVC5's JsonResult but it uses CamelCase and date formatting.
    /// </summary>
    public class MyJsonResult : ContentResult
    {
        private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            Converters = new List<JsonConverter> { new StringEnumConverter() }
        };

        public FindersJsonResult(object obj)
        {
            this.Content = JsonConvert.SerializeObject(obj, Settings);
            this.ContentType = "application/json";
        }
    }
}
select flddate from tblName

select flddate, convert(varchar(12), flddate, 113) as fldDateStr from tblName
<tr ng-repeat="value in Results">                
 <td>{{value.FileReceivedOn | mydate | date : 'dd-MM-yyyy'}} </td>
</tr>
app.filter("mydate", function () {
    var re = /\/Date\(([0-9]*)\)\//;
    return function (x) {
        var m = x.match(re);
        if (m) return new Date(parseInt(m[1]));
        else return null;
    };
});