I have a simple model like:
[MyRequired(Error = "Invalid date time")]
public DateTime LastUpdate
{
get;set;
}
...
and MyRequiredAttribute
class:
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
<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.
How can I convert from dd-MM-yyyy
format to MM/dd/yyyy
format ? Maybe MVC accepts only MM/dd/yyyy
format.
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
<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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.