I want do have my DateTime get displayed without the time.
So I use
item.AD_Date.Date
to cut off the time.
In the Model ( I use MVC) AD_Date is set up like this:
public System.DateTime AD_Date { get; set; }
But I get my date like this:
01.03.2013 00:00:00
What did I do wrong?
The Date property just returns a DateTime with the same date, but at midnight. There's no difference between "a DateTime at midnight" and "a DateTime just representing a date" (unfortunately).
You need to change how your DateTime is formatted to only show the date - either by annotating the model or by changing the view.
(Alternatively, use my Noda Time library which has different types for the different kinds of data you want to represent. I haven't tried using it with MVC, but at least for the formatting side it should work okay...)
If someone is facing the same problem, here is my formatting :
#String.Format("{0:yyyy-MM-dd}", item.AD_Date)
Related
I'm having a terrible time adding a date to a view. I want the user to be able to type in a date like 6/30/15 or 6/30/2015, but the validation keeps failing if I use the 2 digit date. I've tried to "tell" MVC to accept a two digit date, but it always fails. Can someone explain how to get this right?
My view is set up like this (including just the troublesome date field for brevity):
#model Models.CompanyContracts
#Html.EditorFor(m => m.BegDate)
I started out with a simple model with a date field defined like this:
public DateTime? BegDate { get; set; }
I got an error saying "The field BegDate must be a date" when I entered the date as 6/30/15 or 06/30/15; I did not get the error when I entered 6/30/2015 or 06/30/2015.
So I tried to add a type and display attribute as describe
Here: Format datetime in asp.net mvc 4
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:M/d/yy}", ApplyFormatInEditMode = true)]
I get the same error trying to enter 6/30/15. I tried several different formats, including a datatype and not a displayformat, including a displayformat and not a datatype, but I get the "The field BegDate must be a date" error everytime.
I tried a regular expression validation and it also failed (both the MVC validation and the regular expression; obviously the regex I got from http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5&AspxAutoDetectCookieSupport=1 needs some work):
[RegularExpression(#"^((0?[13578]|10|12)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[01]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1}))|(0?[2469]|11)(-|\/)(([1-9])|(0[1-9])|([12])([0-9]?)|(3[0]?))(-|\/)((19)([2-9])(\d{1})|(20)([01])(\d{1})|([8901])(\d{1})))$", ErrorMessage = "Invalid Date")]
public DateTime? BegDate { get; set; }
Can someone tell me how to get MVC to accept entering dates with 2 or 4 digits?
One other note, no external date pickers. I need to get this working with a simple entering of text. Once I can prove that can be done, my boss might allow me to spend some time figuring out a date picker. Thanks!
-- Update 7/20/15 --
Anyone have suggestions for this? I haven't found anything online that's helped me. I'd appreciate any feedback at this point to give me somewhere else to look for a solution.
-- Update 7/29/15 --
Still looking for suggestions. Any ideas at all?
I think it's simply not possible without some kind of twist.
How is the engine/code suppose to know which year it is if you enter just 15 as the year.
Is it 2015 ? 1915 ? 2115 ?
You need to pass the 4 digits to create the dates, if you only have 2 digits you cannot create the date.
So in your case what I would try is to default and hide the '20' prefix (assuming you can only enter a date for 2000's) to your 2 digits year input (or add it somehow using a bit a javascript).
If I have a property in a view model like:
[DataType(DataType.DateTime)]
public DateTime? MyDate{ get; set; }
And a validation rule like this:
public class YourDetailsViewModelValidator : AbstractValidator<YourDetailsViewModel>
{
public YourDetailsViewModelValidator()
{
RuleFor(x => x.MyDate)
.InclusiveBetween(startDate, endDate)
.WithMessage("error");
}
}
Why does the error fire regardless of what date is input?
I did see a similar thing was happening enter link description herebut the answer was ultimately accepted so I'm hoping it can be made to work properly.
Error can be explained by difference in jquery.validate plugin date formatting and MVC helpers formatting. Just look in html generated by your view, and use
[DisplayFormat(DataFormatString="...")] // format string instead of dots
to make data-val-min and data-val-max attributes conform input value format (if they not, of course).
If value and validation attributes format are the same, but validation still fails - make sure that jquery.validate has appropriate format. In this case you should change ASP.NET MVC application culture to conform jquery.validate format, or vice versa — change jquery.validate format to conform application.
Similar questions asked on SO:
First
Second
.NET date formatting options available here.
I'm developing a web project with service and repository layers in ASP.NET MVC 2.
I'm using Entity Framework.
I have two generated EF classes. Namely, Company and User.
Company has two fields CompanyID {int} and CompanyName {string}.
User has three fields UserID{int}, UserName{string}, BirthMonth{smallint,can be null} and CompanyID{int, this is a foreign key of Company}
I have a view for displaying UserName, Month and CompanyName. And also, this same view should include another model, namely Messages (MessageTitle, RecievedDate, ReceivedFrom) I would like to view BirthMonths as month names (January, February, etc.)
I'm stuck at converting short? to short and displaying months as names (ie. January, February) other than numbers.
Give this a try(I didn't test it, but found similiar in a few web searches).
string month = String.Empty;
if(BirthMonth.HasValue)
{
DateTime date = new DateTime(1,(int)BirthMonth.Value,1);
month = date.ToString("MMMM");
}
else
{
// month = some default value here;
}
Edit to add:
To convert short? to short specifically:
short myShort = BirthMonth.HasValue ? BirthMonth.Value : 0;
short? to short can be done using GetValueOrDefault(); to get the non-nullable form, and to get the month name, write a quick converter to convert the number to month name... There may be something within DateTime.ToString to give this to you too.
I want to use Data Annotations to validate DateTime fields, but I'm running into problems. According to documentation on MSDN (http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.rangeattribute.aspx), the following should do the job
[Range(typeof(DateTime), "1/2/2004", "3/4/2004",
ErrorMessage = "Value for {0} must be between {1} and {2}")]
However, this marks any date I enter as invalid!
At first I thought it was not picking up UK dates (when I tried 26/2/2004) but I can't even get it to use dates such as 2/2/2004.
I'm using the dataannotations within MVC2, and using the MicrosoftAjax framework for clientside validation.
Any suggestions?
Thanks
Well, a few years have gone past and I revisited this same issue with MVC4 and I can tell you that it has apparently been resolved.
I created a very simple default MVC4 site, and gave a date member the following attributes
[Required]
[DataType(DataType.Date)]
[Range(typeof(DateTime), "1/2/2004", "3/4/2004", ErrorMessage = "Value for {0} must be between {1} and {2}")]
public DateTime BlogDate { get; set; }
The validation now works perfectly under UK data system, disallowing a date 2/1/2004, allowing a date of 4/3/2004 or 26/3/2004.
The template I was using took advantage of code-first EF4, but I don't have any reason to suspect that it hasn't been fixed generally, since the javascript is working properly too.
So if you are using MVC2 this may still be a problem, but the best solution which I've found is to use MVC4 as long as it is available to you.
As far as i know the RangeAttribute can only validate number on client side, you'll have to write a custom javascript validator for this to work...
check out http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx for an example on how to do this.
I have a search form with a DateTime search criterion, plus some other criteria:
<form method="get" action="/app/search">
<input type="text" value="13/01/2010" name="BeginDate"/>
<input type="text" value="blah" name="SomeOtherCriterion"/>
<form>
So I have a Search controller with a default Action (let's call it Index) and with a SearchCriteria parameter.
public class SearchController
{
public ActionResult Index(SearchCriteria searchCriteria) {//blah }
}
public class SearchCriteria
{
public DateTime BeginDate {get; set;}
public string SomeOtherCriterion {get; set;}
}
Now if I want to create an ActionLink, passing in a SearchCriteria value, thus:
Html.ActionLink("Search", "Index", searchCriteria)
I get the BeginDate query string parameter in US format. Looking on Google and poking around in System.Web.Routing using Reflector it seems to be because it uses the InvariantCulture, so there's nothing I can do about it.
It seems like noone has asked this question before so I guess I'm doing something very stupid.... Please help!
EDIT: Pass in SearchCriteria to ActionLink rather than anonymous object to show why I can't just do the custom ToString() myself.
Given that the framework appears to be hard-coded to handle this piece of data using InvariantCulture, I don't think there's much you can do to make it work transparently.
There is one ugly option - download the MVC source and rip out the code for all the offending classes from Route down to ParsedRoute to create your own RouteBase implementation that does what you need.
If I absolutely had to keep the DateTime declaration on the SearchCriteria class, then that's the route (sorry for the pun) I would choose.
However, a far easier solution would be to change your SearchCriteria class to use a slightly different declaration for the DateTime field, based on a type like this:
public class MyDateTime
{
public DateTime Value { get; set; }
//for passing MyDateTime in place of a DateTime without casting
public static implicit operator DateTime(MyDateTime instance) { return instance.Value; }
//so you can assign a MyDateTime from a DateTime without a cast
//- e.g. MyDateTime dt = DateTime.Now
public static implicit operator MyDateTime(DateTime instance) { return new MyDateTime() { Value = instance }; }
//override ToString so that CultureInfo.CurrentCulture is used correctly.
public override string ToString()
{
return Value.ToString(CultureInfo.CurrentUICulture);
}
}
In theory you should be able to roll out this change without too much fuss.
The big work could be if you have a lot of code that uses members (e.g. .Days etc) of the DateTime instance in SearchCriteria: you either have to reproduce those members on MyDateTime, wrapping around the inner DateTime Value or change all the code to use .Value.Member.
To avoid issues related to Regional Settings and "Culture",
I treat date and time as separate unbound fields and then
assemble them into DateTime in my Controller.
Example:
Year [ ] Month [ ] Day [ ]
I always present separate textboxes for year, month, and day, in that order so that there can be no confusion between U.S. format (month/day/year) and more or less the rest of the world's format (day/month/year).
Can you provide a formatted date in your ActionLink? Try this:
Html.ActionLink("Search",
"Index",
new {BeginDate =
DateTime.Now.ToString("d", new CultureInfo("pt-BR");})
Of course this changes BeginDate to a string instead of a DateTime... but maybe that will work for you?
We use ISO ("s" in a format string -- YYYY-MM-DDTHH:MM:SS) format for this. It works correctly, and JavaScript can handle it as well.
Perhaps you could use a Model Binder to format and parse the date? Just re-read the article and noticed that it does not format the date...Probably not going to work out. I'll leave the answer though in case it provides any unintentional inspiration :)
poking around in System.Web.Routing using Reflector it
seems to be because it uses the
InvariantCulture
Are you realy shure about this? The parts of Modelbinding and UrlBuilding I checked used CurrentCulture. Can you check what happens if you set the CurrentCulture before rendering the link?
Get the ASP.NET MVC 1.0 book written by Scott Hanselman, Scott Guthrie, Phil Haack, and Rob Conery. They actually do this exact scenario in the book. They use a specific route. I am looking at it right now on page 216.
They do it by breaking up day, month, and year. Then it is your responsibility to use those values as they come back.