Removing time from datetime in C # and saving date and time format

How can I remove the time from datetime and save the result in datetime format? I do not want to show the time.

Say I have

string d = "2/27/2013 4:18:53 PM" 

How to save output in a DateTime variable with only date, not time.

I can use ToShortDateString (), but then it returns a string, not a datetime.

My ultimate goal is to sort the chronological date column, which can only be done if all records are in date and time format, and not in a row.

0
c #
May 01 '13 at 9:18
source share
4 answers

The Date property of the DateTime structure will give you a date, but will always have a time component representing midnight ("00:00:00"). If you start with a line, you can work with something like this:

 DateTime d = DateTime.Parse("2/27/2013 4:18:53 PM").Date; // 2/27/2013 12:00:00 AM 

Just make sure that you are comparing on DateTime objects (i.e. omit all use cases of ToString() ).

Alternatively, you can format the date in "sortable" format:

 string d = DateTime.Parse("2/27/2013 4:18:53 PM").ToString("s"); 

or

 string d = yourDateTime.ToString("s"); 

In the above case, d will be 2013-02-27T16:18:53 . When sorted alphabetically, the rows will be in chronological order.

+9
May 01, '13 at 21:20
source share
 DateTime dt = DateTime.now(); (To get Any Date) string datewithMonth= dt.ToString("MMMM dd, yyyy"); string onlyDate = DateTime.Parse(datewithMonth).ToShortDateString(); 

Here we get the result as 1/1/2014 . So that we can perform the select operation on sql as follows:

 searchQuery = "select * from YourTableName where ColumnName = ' " + onlyDate + " ' "; 
+3
Sep 15 '14 at 16:51
source share

Just as simple:

 d.ToString("mm/dd/yyyy"); DateTime date = DateTime.Parse(d); 
+1
May 01, '13 at 21:23
source share

How about removing time in a culture: -

  var submissionDateData = DateTime.Now.ToShortDateString(); var submissionDate = DateTime.Parse(submissionDateData, CultureInfo.CreateSpecificCulture("en-GB")); 

The first line gives 02/11/2015

The second line gives 02/11/2015 12:00:00 AM

Do you need to do line splitting on this or is there a way to get rid of time?

+1
Feb 11 '15 at 18:02
source share



All Articles