gpt4 book ai didi

c# - 从 MVC Controller 返回 Json 但日期格式在 javascript 中不正确

转载 作者:搜寻专家 更新时间:2023-11-01 04:38:35 25 4
gpt4 key购买 nike

我在一个项目中工作,我使用数据库中的数据创建一个网格,在我的 Controller 中我有这段代码

List<IEmployeeEntity> list = new Employee(connectionString).GetEmployeeRecord();

它向我返回带有某个日期的员工列表,我进一步使用 return Json(list); 将其转换为 Json;但是我在我的 java 脚本网格中得到的日期格式如/Date(1325075075113)/我的 javascript 代码就像

$.ajax({
url: ../getRecord,
type: 'POST',
data: {},
async: false,
success: function (result) {
if (result !== "") {
Create Grid
}
}
});

最佳答案

我为这种情况创建了两个扩展方法

/// <summary>
/// Converts the value of the current System.DateTime object to its equivalent string representation using the specified format and culture-specific format information.
/// </summary>
/// <param name="date">DateTime instance</param>
/// <param name="format">A standard or custom date and time format string.</param>
/// <returns>A string representation of value of the current System.DateTime object as specified by format and provider.</returns>
public static string ToFormatString(this DateTime date, string format) {
return date.ToString(format, new CultureInfo("en-US"));
}

/// <summary>
/// Returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
/// </summary>
/// <param name="dt">Date Time</param>
/// <returns>Returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)</returns>
public static double UnixTicks(this DateTime dt) {
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return ts.TotalMilliseconds;
}

您可以选择其中任何一个。要将日期转换为字符串,您可以简单地做,

 var dateString = myDate.ToFormatString("dd/MM/yyyy");

您不必担心机器的文化。

希望对你有帮助。

关于c# - 从 MVC Controller 返回 Json 但日期格式在 javascript 中不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9191580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com