This question already has answers here:
Format datetime in asp.net mvc 4
(3 answers)
Closed 8 years ago.
I am trying to format date time attribute in MVC 4 class like this :
[Required]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime DateOfBirth { get; set; }
but not work DateOfBirth attribute accept date format month before day (EX:accept 1/27/1990 and not accept 27/1/1990)
I am searching for answers and trying many solution but not work like
enter link description here
using html helper:
#Html.TextBoxFor(Model => Model.DateOfBirth)
I appreciate any help thanks
The [[DisplayFormat] attribute is only for how to display the value in the view. It has nothing to do with the format that will be accepted. You can write some code to accept a string and in the server parse that back into a proper DateTime property. Store your DateTime, then when you go to display it back to the user you use your [[DisplayFormat] attribute
what you would do is use Regular Expressions to verify the user inputed a number then "/" then number then "/" then number.
Obivously you are not the first one to run into something like this , this is why datepickers are so commnly used , they force the user to pick a date and format it appropiatly
If your using #Html.TextBoxFor() to render the control, then [DataType(DataType.Date)] and ApplyFormatInEditMode = true in the [DisplayFormat] attribute is not really necessary. These are only applicable when you use #Html.EditorFor() to render the browsers date picker, in which case the format must be "yyyy-MM-dd" in order to display correctly in all browsers.
If you want to display the formatted date in a textbox, use
#Html.TextBoxFor(Model => Model.DateOfBirth, "{0:dd/MM/yyyy}")
Note if you post back "27/1/1990" (27th January 1990) and the current culture of the server has the date format "MM/dd/yyyy" then you will need a custom model binder to correctly bind the date. Refer example here
Related
I m using MVC 5 and requirement is as below:
My viewModel property as below:
public DateTime? Date { get; set; }
This is optional field so user can manually type date (dd/MM/yyyy) format or leave it blank.
Requirement is in-case user enter the invalid date it should get checked on client side to validate that date is in valid format. If not then form should not get submitted.
I tried following but it does not work.
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
Tried regular expression but still does not work. or work partially ..e.g. shows date wrong in I enter sdkjshdkj but validate it if format is wrong or even if I enter 22.
I don't want to use Jquery Calendar
Try to use in view TextBoxFor instead of EditorFor
#Html.TextBoxFor(model => model.Date, "{0:dd-MM-yyyy}", new { #class = "form-control" })
last days I have a quite hard time to convince MVC5 project to work with dates as I would like to. After intensive googling I've tried numerous attepmts to make it work properly, but without success.
Here is the problem:
I need to display and edit dates on my webpage in format dd.MM.yyyy (i.e. 15.07.2015). For editing I also need to use jquery ui datepicker. The thing here is that I've been able to successfully set that datepicker to display date in requested format, also the jquery validation is now correctly validating the date in given format. So as for UI so far so good. The problem appeared in moment, when I clicked submit button - there was an error message like:
The value '15.07.2015' is not valid for Start Date.
After brief investigation I've found that when the date is passed to server it has switched format - instead of dd.MM.yyyy the date is treated like MM.dd.yyyy. In other words the error pops up only when the day part of date is higher than 12.
Here are some highlights from my code:
In my model for date I have this:
[Required]
[Display(Name = "Start Date")]
[DataType(DataType.Date)]
[UIHint("Date")]
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}", ApplyFormatInEditMode = true)]
public DateTime DateStarts;
Which I believe is everything I need to do to make that date display in specified format and also force users to fill the textbox with date in right format.
As given in [UIHint("Date")], I have my own template for rendering textbox for editing date. The implementation of that template is following:
#model Nullable<DateTime>
#{
DateTime dt = DateTime.Now;
if (Model != null)
{
dt = (System.DateTime)Model;
}
#Html.TextBox("", dt.ToString("dd.MM.yyyy"), new { #class = "form-control datecontrol", type = "text", data_val_date = "Field must have format dd.MM.yyyy" })
<i class="fa fa-calendar form-control-feedback lowerzindex"></i>
}
The jquery datepicker has following implementation:
$('.datecontrol').datepicker({
onClose: function () { $(this).valid(); },
minDate: "-1M",
dateFormat: "dd.mm.yy",
});
So even the datepicker knows how the format should look like.
The last component is the validation by jquery.validation:
$.validator.addMethod(
'date',
function (value, element, params) {
if (this.optional(element)) {
return true;
};
var result = false;
try {
$.datepicker.parseDate('dd.mm.yy', value);
result = true;
} catch (err) {
result = false;
}
return result;
},
''
);
I know that the date is passed to server in some culture neutral format, but I thought that when I decorated code on numerous places with the requested format, this will ensure that the conversion into that culture neutral format will be done right. Or am I missing something else ?
Thanks
Your problem lies in the fact that you have not set proper Culture for your application. Your request end-up executing under culture that has month-day-year order (probably under en-US) causing you a problem.
The easiest solution is to set set the culture that actually has day-month-year order and . as date separator in your web.config, for example:
<configuration>
<system.web>
<globalization uiCulture="de-DE" culture="de-DE" />
...
https://msdn.microsoft.com/en-us/library/bz9tc508%28v=vs.140%29.aspx
The MVC uses current culture when parsing and binding posted data to your models/parameters.
It is advised to use same date separator across entire scope - html, client, javascript, server culture, ...
I have a View that renders a list of items, and each item contains a Date property.
<%:Html.HiddenFor(m => m.Items[j].Date)%>
A number of other properties are hidden or shown, and the user is able to enter comments against any item and save these comments to the database. It's a 'bulk edit' type View.
I've used these Views before to good effect, but I'm having a problem with the Date property because it renders thus
<input name="Items[3].Date" type="hidden" value="3/05/2012 11:56:48 AM" />
The problem is that I need to use the DateTime as a part of the primary key for this data item. I could truncate the milliseconds in the database to allow the match but there is no guarantee that there will only be one data point per second.
How do I ensure that the hidden input field for my DateTime retains all of the property's information, including the milliseconds component?
well do you really need to use
<%:Html.HiddenFor(m => m.Items[j].Date)%>
why not just keep it simple
<input type="hidden" name="Items[<%:j%>].Date" value="<%:model.Items[j].Date.ToString("dd/MM/yy/ HH:mm:ss.fffff")%>"/>
I've not had any success forcing the format of a DateTime in a HiddenFor field.
The DisplayFormat attribute can force the format for a DisplayFor field but has no effect on a HiddenFor field.
I resorted to the below no-quite-a-hack to get this to work - serialize and deserialize the ticks property to ensure the true time is retained.
public long DateTicks
{
get
{
return this.Date.HasValue ? this.Date.Value.Ticks : 0;
}
set
{
if (value == 0)
this.Date = null;
else
this.Date = new DateTime(value);
}
}
Use
<%:Html.HiddenFor(m => m.Items[j].Date.Ticks)%>
Use the DisplayFormat attribute on the Date property in your model, and spell out the milliseconds in the format string:
[DisplayFormat(DataFormatString = "{0:yyyyMMddhhmmssfff}")]
Controller's Code
int No= Convert.ToInt32(reqCookies["NO"].ToString());
Student stud = db.Students.Single(n => n.No == No);
return View(stud);
Im passing the No after the user logs In and want the record of that logged In person to be displayed which i have successfully done.My issue is again with the Date.When the record of the Logged In user is displayed the Date of birth is displayed along with the time.Like this 2/19/2001 12:00:00 AM, instead i only want the date part and not time something like this 19/2/2001.
To achieve this i have tried to convert the date in dd/MM/yyyy format
DateTime DOB=stud.DOB.tostring("dd/MM/yyyy");
Getting Error:No Overload for method 'ToString()' takes 1 Argument
Code in my View is like this:
<td>#Html.DisplayFor(model => model.DOB.ToString())</td>
And when i try to change the format in the View
<td>#Html.DisplayFor(model => model.DOB.ToString("dd/MM/yyyy"))</td>
Getting Error:No Overload for method 'ToString()' takes 1 Argument
Where can i make the conversion and how to truncate the time Part from getting displayed.
You could use DisplayFormat in the model to format your date:
[DisplayFormat(DataFormatString = "{0:dd/mm/yyyy}")]
public DateTime myDate { get; set; }
And then in the view:
<td>#Html.DisplayFor(model => model.DOB)</td>
Update:
Alternatively, since the DisplayFor() will simply output the date without any tags, you could just display the date without the use of templated helpers:
#Model.myDate.ToString("dd/MM/yyyy")
Or to display in a textbox you could use:
#Html.TextBox("Date", Model.myDate.ToString("dd/MM/yyyy"))
I want to convert string date to system datetime in C#. The user enters date through textbox and it should be converted as to datetime. I trid following code but its not working...
DateTime ToDate = Convert.ToDateTime(txtToDate.Text);
DateTime FromDate = DateTime.Parse(txtFromDate.Text);
It shows the following exception
"String was not recognized as a valid DateTime."
How to do this...???
You could use DateTime.ParseExact(). That way you can specify the format of the input string, so it will be parsed correctly, for example:
dateString = "Sun 15 Jun 2008";
format = "ddd dd MMM yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
whatever user enters in your textbox that should be in valid date format, otherwise write your own function to make it in valid format. then Convert it into DateTime format .
for different format you can check this :
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
for more help you can check similar question on this site :
Validate a DateTime in C#
You can of course parse the user's input and rely on the users to always enter a correct date. But I'd recommend to use a specific control for entering a date, such as the calendar control of the ajax control toolkit.
By using such a control, you can prevent invalid input and it's also much easier for the user. If you search for DatePicker or similar, I'm sure you can find lot's of other similar controls.
Ask the user to enter his datetime in a particular format into textbox i.e., either "ddMMyyyyhhmmss" or "dd/MM/yyyy hh:mm:ss tt" or "dd-MM-yyyy hh:mm:ss tt" or some other formats and use the help of following code to convert in to a Valid datetime.
DateTime ToDate = DateTime.ParseExact(txtToDate.Text, <User DateTime format as String>,
System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Instead, if the above coding makes complicated then you can try DateTime.TryParse() also
First of all you have to validate text box value that it is valid or not, you can use ajax MaskeditExtender control for that and restrict the use enter only require date formate.
DateTime dt = Convert.ToDateTime(date);
here date is in string.