日期格式将参数从 Jquery 切换到控制器
Date Format Switched Passing Parameter From Jquery to Controller
我认为我正在使用以下内容:
var myDate = $(inpDateCompleted).val();
alert(myDate)
var url = '@(Url.Action("HoursByDay", "DashBoard"))?dateCompleted=' + myDate;
alert(url)
两个警报均正确显示日期格式为 01/11/2011(11 月 1 日)。但是,一旦日期通过上述 url 传递到我的控制器事件中,日期就不正确为 11/01/2011(1 月 11 日):
[HttpGet]
public ActionResult HoursByDay(DateTime dateCompleted)
{
var s = ExecuteSqlCommand2(dateCompleted);
return Content(s, "application/json");
}
并且产生的数据不正确。我该如何纠正?
根据建议,我使用以下方式设置文化:
var localizationOptions = new RequestLocalizationOptions
{
// Set options here to change middleware behavior
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-NZ"),
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-NZ"),
}
};
app.UseRequestLocalization(localizationOptions, defaultRequestCulture: new RequestCulture("en-NZ"));
如果您知道日期字符串将始终采用 dd/MM/yyyy
格式,则可以使用 DateTime.TryParseExact
方法从字符串构建日期时间对象。将您的 Action 方法参数更改为字符串并使用 pattern/format.
解析该字符串
[HttpGet]
public ActionResult HoursByDay(string dateCompleted)
{
DateTime parsedDate;
if(DateTime.TryParseExact(dateCompleted,"dd/MM/yyyy",CultureInfo.CurrentCulture,
DateTimeStyles.None,out parsedDate))
{
// parsedDate is a valid DateTime object now
var s = ExecuteSqlCommand2(parsedDate);
return Json(s);
}
else
{
// could not create a valid DateTime object from inputString
// to do :return something
}
}
我认为我正在使用以下内容:
var myDate = $(inpDateCompleted).val();
alert(myDate)
var url = '@(Url.Action("HoursByDay", "DashBoard"))?dateCompleted=' + myDate;
alert(url)
两个警报均正确显示日期格式为 01/11/2011(11 月 1 日)。但是,一旦日期通过上述 url 传递到我的控制器事件中,日期就不正确为 11/01/2011(1 月 11 日):
[HttpGet]
public ActionResult HoursByDay(DateTime dateCompleted)
{
var s = ExecuteSqlCommand2(dateCompleted);
return Content(s, "application/json");
}
并且产生的数据不正确。我该如何纠正?
根据建议,我使用以下方式设置文化:
var localizationOptions = new RequestLocalizationOptions
{
// Set options here to change middleware behavior
SupportedCultures = new List<CultureInfo>
{
new CultureInfo("en-NZ"),
},
SupportedUICultures = new List<CultureInfo>
{
new CultureInfo("en-NZ"),
}
};
app.UseRequestLocalization(localizationOptions, defaultRequestCulture: new RequestCulture("en-NZ"));
如果您知道日期字符串将始终采用 dd/MM/yyyy
格式,则可以使用 DateTime.TryParseExact
方法从字符串构建日期时间对象。将您的 Action 方法参数更改为字符串并使用 pattern/format.
[HttpGet]
public ActionResult HoursByDay(string dateCompleted)
{
DateTime parsedDate;
if(DateTime.TryParseExact(dateCompleted,"dd/MM/yyyy",CultureInfo.CurrentCulture,
DateTimeStyles.None,out parsedDate))
{
// parsedDate is a valid DateTime object now
var s = ExecuteSqlCommand2(parsedDate);
return Json(s);
}
else
{
// could not create a valid DateTime object from inputString
// to do :return something
}
}