blue piranha
blue piranha

Reputation: 3874

removing time from datetime in c# and retaining datetime format

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

Say I have

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

How can I store the output in a DateTime variable with only the date and not time.

I can use ToShortDateString() but then it return a string and not datetime.

My ultimate goal is to sort the date column chronologically which can only be done if all the entries are in datetime format and not string.

Upvotes: 1

Views: 42579

Answers (4)

user1902142
user1902142

Reputation:

As easy as this:

d.ToString("mm/dd/yyyy");
DateTime date = DateTime.Parse(d);

Upvotes: 1

Craig
Craig

Reputation: 1794

What about removing the time in culture:-

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

First line gives 02/11/2015

Second line gives 11/02/2015 12:00:00 AM

Do you have to do a string split on this or is there a way to get rid of the time?

Upvotes: 1

Varun Tej Reddy
Varun Tej Reddy

Reputation: 41

DateTime dt = DateTime.now();      (To get Any Date)

string datewithMonth= dt.ToString("MMMM dd, yyyy");

string onlyDate = DateTime.Parse(datewithMonth).ToShortDateString();

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

searchQuery = "select * from YourTableName where ColumnName = '  " + onlyDate + " '   ";

Upvotes: 4

Cᴏʀʏ
Cᴏʀʏ

Reputation: 107536

The Date property of the DateTime struct will give you a date but it will always have a time component that represents midnight ("00:00:00"). If you're starting with a string, you might be able to 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 you perform your comparison on DateTime objects (i.e. omit all usages of ToString()).

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

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

or

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

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

Upvotes: 10

Related Questions