format datetime value in C# - asp.net-mvc-3

i want to format date time value in this format ("yyyy/MM/dd")
below is the code, m using to do so
DateTime? date = DateTime.Now;
DateTime? formattedDate = Convert.ToDateTime(date.Value.ToString("yyyy/MM/dd"));
Console.WriteLine(formattedDate);
Console.ReadLine();
the code work fine but you can see in the above code that i have declared datetime variable as null which in reverse causing the problem
please suggest what i am doing wrong in the above code.
as i am getting the output as this 9/10/2012 12:00:00 AM
Thanks,
Aaman

The problem is that what you call formattedDate is actually yet another instance of a DateTime. There's no notion of format inside the native .NET DateTime structure. You can talk about formatting only when you convert it to a string:
DateTime date = DateTime.Now;
string formattedDate = date.ToString("yyyy/MM/dd"));
Console.WriteLine(formattedDate);
or if you want to use a nullable DateTime:
DateTime? date = DateTime.Now;
string formattedDate = date.Value.ToString("yyyy/MM/dd"));
Console.WriteLine(formattedDate);
But since your question is tagged with asp.net-mvc-3, there are other ways to format values. For example using the [DisplayFormat] attribute on your view model:
[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd}", ApplyFormatInEditMode = true)]
public DateTime? Date { get; set; }
and in your view if you want to display the value of your view model:
#Html.DisplayFor(x => x.Date)
or if you want to generate an input field with properly formatted value:
#Html.EditorFor(x => x.Date)

Related

how can i convert datetime exactly to sql server datetime using linq

I have two fields in Model class
public DateTime START_DATE { get; set; }
public DateTime END_DATE { get; set; }
and a Class
string format = "yyyy-MM-dd hh:mm:ss";
string startdate = timesheetModel.START_DATE.ToString(format, DateTimeFormatInfo.InvariantInfo);
string enddate = timesheetModel.END_DATE.ToString(format, DateTimeFormatInfo.InvariantInfo);
var weekid = from data in db.WEEK_CALENDER
where data.WEEK_START_DT ==Convert.ToDateTime(startdate) && data.WEEK_END_DT == Convert.ToDateTime(enddate)
select data.ID;
But Getting Error Convert.ToDateTimes is not possible in linq
and Also in Sql Server as format like
2014-03-03 00:00:00.000
I Have tried in different ways, but i think it needs exact same format of sql server format.
and Tried in that format also , but not getting.
pls help me anyone.
You don't need to convert your datetime to string, this can only cause trouble
public DateTime START_DATE { get; set; }
public DateTime END_DATE { get; set; }
var weekid = from data in db.WEEK_CALENDER
where data.WEEK_START_DT == START_DATE && data.WEEK_END_DT == END_DATE
select data.ID;
Unless you are managing different type of calendar, weeks don't overlap and they all contain 7 days, so you should only need to check the WEEK_START_DT (or only WEEK_END_DT) and you will only get 1 week, so you could do this instead :
var weekid = db.WEEK_CALENDER.Single(data => data.WEEK_START_DT == START_DATE).ID;
An other idea, your method receives a single date, and if returns the weekId which contains this date, it doesn't have to be the specific start of the week, it could be any date. This won't work of course if you are managing different type of weeks in your table.
var weekid = db.WEEK_CALENDER.Single(data =>
data.WEEK_START_DT <= A_DATE
&& data.WEEK_END_DT >= A_DATE
).ID;

Datetime validation with custom format. Troubles with '.' separator

In my web application (asp.new mvc) I try to make validation for date field.
If I use this
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
or this
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
it works. But if I try to separate using '.' separator
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
I have an issue. jQuery validation says that I have to enter date if I try '01.01.2001'.
Here is view
<div class="ElementDiv">
#Html.LabelFor(m => m.Filter.PeriodBeginFrom, new { #class = "Labels" })
#Html.EditorFor(m => m.Filter.PeriodBeginFrom, new { #class = "TextBoxes" })
#Html.ValidationMessageFor(m => m.Filter.PeriodBeginFrom, null, new { #class = "Errors" })
</div>
Why? With all other separators it works. What a problem is with '.' separatior?
Update 1: It seems that validation does not work properly. If I have this attribute at my model
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime? PeriodBeginFrom { get; set; }
and we pass DateTime object to model, it will be displayed at textbox with '.' like '12.12.2012' and not like I was waiting '12/12/2012'. Hope you'll give me some ideas.
You're looking at a date component. But remember that time components can include seconds and fractional seconds, with a period inbetween. Since dates and times are frequently combined, I would not be surprised if the period is being treated as a special character.
Update:
I went through the following documentation chain:
DisplayFormatAttribute.ApplyFormatInEditMode Property
DisplayFormatAttribute.DataFormatString Property
Formatting Types
Custom Date and Time Format Strings
I expected to see that the period character has a special meaning in the format string. Instead, the documentation doesn't specifically list the period character. That means it should fall in the categry of "Any other character", and therefore, "The character is copied to the result string unchanged."
However, I don't believe it. Fractional seconds occur in time components like 23:59:59.999, and I suspect there is undocumented special treatment of the period character.
Trouble with a format was not with ASP tags and fields but with unobtrusive validation jquery library. I had to overload unobtrusive JavaScript validation method for date for my date format. More details are here
MVC DateTime validation - UK Date format

ASP.NET MVC DisplayFormat for Hour

I have the following TimeSpan variable in my Model class:
[DisplayFormat(DataFormatString = "{0:HH-mm}", ApplyFormatInEditMode = true)]
public TimeSpan StartingHour { get; set; }
But when I call it from my View I got the error:
#Html.DisplayFor(modelItem => item.StartingHour)
System.FormatException: Input string was not in a correct format.
The value of the variable is: "18:00:00".
What should be in my DisplayFormat initialization? And please keep "get hour and minute separately from the time" advices to yourself.
Try: DataFormatString = #"{0:hh\-mm}"
Try using:
DataFormatString ="{0:hh\\:mm}"
Thanks.

How to show a custom error message for DisplayFormat attribute In Asp.Net MVC?

How to show a custom error message for
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
The code in my model is following,
[Display(Name = "When was that document issued?")]
[DataType(DataType.Date, ErrorMessageResourceName = "DocumentIssueDate_DataType",ErrorMessageResourceType = typeof(CustomErrorMessages))]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? DocumentIssueDate { get; set; }
In my View when I enter 201 in the date textbox I get the following error message. How do I modify the error message below.
The value '201' is not valid for DocumentIssueDate.
After a lot of research I had no luck. The only solution was to use RegularExpression.
Instead of using:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
You can use:
[RegularExpression(#"^(3[01]|[12][0-9]|0[1-9])[-/](1[0-2]|0[1-9])[-/][0-9]{4}$", ErrorMessageResourceName = "Date Not Valid")]
The RegularExpression matches the date format dd/MM/yyyy.
regular still not test yes but you can search and edit if need
Try see answers Here. I think DisplayFormat designed not for validation, that is why you can not use it to check if entered string is valid.

Input with date format set from ViewModel and html class attribute

I am working with razor view engine in asp.net mvc3.
Now, I need an input for a DateTime which should display the value in a fixed format (say dd-MMM-yyyy). So I can do:
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MMM-yyyy}")]
public DateTime StartDate { get; set; }
And in the view:
#Html.EditorFor(model => model.StartDate)
But I need to add a class in the input. Which I think is not possible in EditorFor.
So I could use
#Html.TextBoxFor(model => model.StartDate, new { #class = "Date" })
But the display format does not work in this case.
Model can be null. So,
#Html.TextBox("StartDate", string.Format("{0:dd-MMM-yyyy}", Model.StartDate))
will throw NullReferenceException.
ophelia's way is a quicker version of mine. But this way is useful if you're going to have a few date fields in your application. So this is the way i like to do it:
-> In your solution explorer, create a folder inside Shared called "EditorTemplates"
-> In there, add a new (not strongly typed) Partial View. Call it "DateTime".
-> Open this view, and remove any code in there, and throw the following code in there:
#model System.DateTime
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { #class = "date" /* + any other html attributes you want */ })
-> In your ViewModel, your date field should be like this:
[Display(Name = "My Date:"), DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime MyDate { get; set; }
-> In your main view, and any view you want to use a date field, you can just use EditorFor on the property, like so:
#Html.EditorFor(m => m.MyDate)
You can initialize the date field in your controller or set a default date in your viewmodel's constructor.
I use this and its works fine:
#Html.TextBox("ExpiryDate", String.Format("{0:ddd, dd MMM yyyy}", DateTime.Now), new { id = "expirydate" })
Hope this is what you mean/need :)

Resources