Show date part only - c#

I would like to display only the date on the page.
SQL column has type date.
Model
public System.DateTime EndDate { get; set; }
View
#Html.DisplayFor(modelItem => item.EndDate.Date)
This gives me no warnings or errors, however the time is still displaying on the page.

DateTime.Date returns a new instance of DateTime with the time component set to midnight (rather than removing the Time completely), it's only useful for normalizing date/time values and is not intended for display purposes.
Anyway, you don't need DisplayFor, you can render the date directly:
#item.EndDate.ToString("yyyy-MM-dd")

You can use theDate.ToShortDateString() or use a custom date/time string format.
The benefit of ToShortDateString() is that it is CULTURALLY SENSITIVE making your application more accessible.
If you want to use the Html.DisplayFor template helper then you may want to build a ShortDateTime.cshtml display template. Learn more about that here:
https://stackoverflow.com/a/6001836/941058

Try the ToString() date formatters:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Example:
#Html.DisplayFor(modelItem => item.EndDate.Date.ToString("MMMM dd, yyyy")

Related

Posting valid DateTimes from anywhere

I want to create a simple ASP.Net form, that will get birth dates.
I have a model with this property:
[DataType(DataType.Date)]
public DateTime? BirthDate{ get; set; }
and in my view (is using the datepicker):
#Html.LabelFor(model => model.BirthDate)
#Html.TextBoxFor(model => model.BirthDate, new { #class = "form-control date-picker" })
#Html.ValidationMessageFor(model => model.BirthDate, "", new { #class = "text-danger" })
The only one setting on my javascript datepicker is:
format: 'L'
because I want show dates without times.
Now, I can't save, because of the validation error:
The value '12/23/2000' is not valid for BirthDate.
Now, I KNOW, its a globalization error... I need set culture in <globalization> element in web.config, etc...
But, have you noticed I set no formats (except the datepicker format "L")? I want that form get birthdates from people in any country, no a specific culture/format etc.
Is this possible? How can I do it?
Edit:
which date picker are u using?
The JQuery one, but this is not a requeriment, I can change to any datepicker that can easily handle different save formats "yyyy-mm-dd" and display format.
Which locale your server is located and which format do you prefer to work within your MVC code and to persist in database?
I dont know where my customer will host the site, its AWS... I prefer work with en-us.
Assuming that your datepicker can return the selected date in Date() js object. I would suggest to convert the date value in to a standard format like ISO8601. So what you have to do is to attach a onChange event on your date picker and convert the selected Date() value into ISO8601 format. You may assign this converted value to a hidden field (simply date.toISOString()).
MVC .net parser also understand ISO8601 format so when your form data is posted on server it is parsed to correct date value. See this question also.
I have create a jsfiddle using jquery UI datepicker. It uses a altFormat and altField which can be used for internal date format irrespective of whatever date format is shown to user in actual date input field.
Find the jsfiddle here - https://jsfiddle.net/Prasoon1983/kyjvwkLd/2/
$("#dob").datepicker({
altFormat: "yy-mm-dd",
altfield:"#dobInternal"
});
$( "#dob" ).datepicker( "option", "altField", "#dobInternal" );
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<input type="text" id="dob" />
<input type="text" id="dobInternal" />
I have used an input control for display purpose but you can use a hidden input.
Hope it helps.
Make your property as below
[RegularExpression(#"(\d{2}|\d{1})[/](\d{2}|\d{1})[/]\d{4}",ErrorMessage ="Birthday field must be ad dd/mm/yyyy format.")]
public DateTime? BirthDate{ get; set; }
Above regex only for dd/mm/yyyy format.If you need alternatives you must add that sign in [/].
Type of birthdate property of ViewModel can be string now.You can convert it to DateTime when you need
Globalization is really hard. But if you relaying on Javascrip then you can display selected date in one format and send it to server using different one e.g. ISO standard.
On server side I would prepare strict validator - e.g. accept only date in ISO format. When you receive request with some strange input then respond with error (with proper message).

How to save date only from WPF datepicker using c#?

I wanted to save only date in my database. There is a table which holds dates in database and the column which holds date in type of "Date". Now I want to store date from UI,so I placed WPF DatePicker in UI which allows to select date, but whenever I try to get the data from datepicker it shows the date and time.But I want just the dates to be stored in database.
This is the thing i am doing. It is demo code by the way. Can t upload original code. But this explains the thing. you can see in the message box, it shows 14-10-2015 00:00:00 , i want this zeros to be removed.
The dateTime Picker has a property DisplayDate of Type DateTime. This type contains date and time information.
Just use picker.DisplayDate.Date this returns a DateTime value with the TimeOfDay component set to 00:00.00
Edit
Usually you use an SQL Statement to insert or update values in the database. You should use a parametrized SQL statement with an parameter of type DateTime. The SQL API will take care of the conversion form DateTime (.Net type) to your SQL Date type and strip all time information away. It is a good idea to set the time component to 00:00:00 however to avoid any strange "roundings".
Use ToShortDateString() at the end something like:
var date = datePicker.SelectedDate.Value.Date.ToShortDateString();
MessageBox.Show(date.ToString());

To Get Data that its type is Date in C#

In my SQL database, I have BeginDate column of type date (so I want to get only day,month,year).
I add data into database in C#.
I look at Table_Data and everything is fine (for example BeginDate = 05/04/2014).
But when I get this data from database in C# with
string a= dt.Rows[i]["BeginDate"].ToString()
result is: a= 05/04/2014 12:00:00 AM
Why?
I can remove hour in string a with any methods. But why? I want to get only 05/04/2014 from database.
This is a display problem, not a data problem. Use the Formatting features of DateTime.ToString() to display the date in the format that you want.
If the data is coming out of the database in string form, use DateTime.Parse on it first.
Reference
Standard Date and Time Formats
Custom Date and Time Formats

How to convert the date that have been retrieve from DB to only display d/mm/yyyy?

I have this 21/10/1999 value manually inserted into the SQL database and when I retrieve it like this:
txtDOB.Text = readPatient["pDOB"].ToString();
It displays everything along with the time 12:00:00 AM. My data type for my date column is date, not datetime. So why is it displays the time as well?
((DateTime)readPatient["pDOB"]).ToString("d");
For a list of supported formats see: http://msdn.microsoft.com/es-es/library/zdtaw1bw(v=vs.110).aspx
You may try
txtDOB.Text = Convert.ToDateTime(readPatient["pDOB"]).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
Edit: Thanks to comments saw that forgot to cast to datetime
It looks like you got your answer on how to properly format the value to a string without the time portion. But, no one has answered your other question:
So why is it displays the time as well?
This is because of mappings between SQL and .NET. In .NET a SQL "date" is stored in a DateTime object which does have time as well. To see all mappings between SQL and .NET see this: SQL Server Data Type Mappings
you can try this
txtDOB.Text=Convert.toDateTime(readPatient["pDOB"]).ToString("d/MM/yyyy");
You can use the string format parameter of the ToString to achieve any format you like,
like this:
TextBox1.Text =Convert.toDateTime(readPatient["pDOB"]).ToString("d/MM/yyyy");
Click on the datetimepicker then go to properties. There you can format your datetimepicker. Change format to custom (there few selection there) then set custom (provided in the properties menu) table with yy-MM-dd,an
DateTime dt = Convert.ToDateTime(sqdr["invdate"].ToString());
dt.Date; //To get the date only

ASP.NET MVC 3 Binding & Validating Date to html textbox control

I have a SmallDateTime field in my Sql Server 2008 database to store users Birthdays.
On my 'Edit Profile' web page, I have a standard textbox which I want to bind the 'Birthday' date to (excluding the time as this is not required). At present I am binding to the textbox but it is rendering the full Date and Time.
In addition, when the user updates their profile, I want to be able to validate the Birthday textbox, ensuring that the value specified complies to dd/mm/yyyy, and any deviation from that is highlighted via my existing validation summary on the page.
How do I go about:
a) configuring the Birthday property in my ViewModel to display in dd/mm/yyyy format (excluding the time).
b) validate Birthday (based on dd/mm/yyyy format) when the user submits the form?
[DisplayFormat(DataFormatString="{0:dd/MM/yyyy}", ApplyFormatInEditMode=true)]
public DateTime DateOfBirth { get; set; }
This should give you the automatic formatting on the field (without you having to manually do it) and also the validation.
I usually use a string property paired with the DateTime object, something like
public string MyDateStr
{
get
{
return MyDateDate == null ? "" : MyDateDate.ToShortDateString();
}
set
{
// Usually a tryParse for the string value
}
}
I know that is not the canonical way, but up to now, is the fastest I've found.
HTH
M.
EDIT: for the validation stuff see this:other question on SO
a) you can use .ToShortDateString to render your datetime without time. Format still depends on globalization defaults.
b) to validate, you could do it with Data Annotations on your model like this:
[DataType(DataType.DateTime, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy")]
public DateTime Birthday { get; set; }

Categories

Resources