[英]Convert a client datetime to server datetime in ASP.NET MVC
I have a simple model like: 我有一个简单的模型,例如:
[MyRequired(Error = "Invalid date time")]
public DateTime LastUpdate
{
get;set;
}
...
and MyRequiredAttribute
class: 和
MyRequiredAttribute
类:
public class MyRequiredAttribute: RequiredAttribute {
public override IsValid(object value) {
//value get from request is `01/01/0001 00:00:00 ...`
DateTime parsedTime = DateTime.Parse(value.ToString());
// here throws exception
}
}
and on Javascript side, using Datepicker
plugin, I used 在JavaScript方面,我使用
Datepicker
插件
<input type="text" id="LastUpdate" name="LastUpdate" class="datepicker" value="<%=DateTime.Now.ToString( "dd-MM-yyyy" )%>" />
and 和
$(".datepicker").datepicker({ dateFormat: 'dd-mm-yy' });
Every time, I receive from request 01/01/0001
value and throws an error that format is not correct. 每次,我都从请求
01/01/0001
接收值,并抛出一个格式不正确的错误。
How can I convert from dd-MM-yyyy
format to MM/dd/yyyy
format ? 如何将
dd-MM-yyyy
格式转换为MM/dd/yyyy
格式? Maybe MVC accepts only MM/dd/yyyy
format. 也许MVC仅接受
MM/dd/yyyy
格式。
In your Model use following way 在您的模型中使用以下方式
public string LastUpdate
{
get;set;
}
Now in your Controller Bind following way if it is in Editing Mode than 现在在您的控制器中如果它处于编辑模式,则按以下方式绑定:
Model.LastUpdate = FetchDateFromServer.ToString("dd-MM-yyyy")
otherwise
Model.LastUpdate = DateTime.UtcNow.ToString("dd-MM-yyyy")
Now from your View Remove value from input type="text" it will take if it is strongly typed 现在从您的“视图”中删除输入type =“ text”的值,如果它是强类型的
<input type="text" id="LastUpdate" name="LastUpdate" class="datepicker" />
I hope it will work as it is perfectly working in my project 我希望它能在我的项目中正常工作
I think you should write 我想你应该写
$("#dates").datepicker("option", "dateFormat", "dd-mm-yy"); // it will give format dd-mm-yy
or 要么
$("#dates").datepicker("option", "dateFormat", "mm-dd-yy"); // it will give format mm-dd-yy
Insted of 插入
$(".datepicker").datepicker({ dateFormat: 'dd-mm-yy' });
or on server side You can do something like this 或在服务器端,您可以执行以下操作
const string dateformate = "dd/MM/yyyy";
var reachDate = DateTime.ParseExact(dates, dateformate, CultureInfo.InvariantCulture);
This will convert any date to dd/MM/yyyy format. 这会将任何日期转换为dd / MM / yyyy格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.