views:

118

answers:

6

How can I "trim" a value of a DateTime property in c#?

For example, when I get a date it is of the format "10/1/2010 00:00:00".

How can I "trim" 'Time' 00:00:00 without converting this to a String?

Since I use a property of type DateTime to manipulate this, I don't need to convert to String.

Any help is appreciated.

+5  A: 
var dt = DateTime.Now;    // 10/1/2010 10:44:24 AM
var dateOnly = dt.Date;   // 10/1/2010 12:00:00 AM
codekaizen
And/or dt.ToShortDateString(); when it comes time to display.
Jacob Proffitt
This doesn't answer the question. Of course the question doesn't have an answer since a DateTime always has a time.
Kevin Gale
@Kevin Gale: I disagree. I think it gets to the intent of the OP. Perhaps he will clarify the question or comment on this post.
codekaizen
@codekaizen: I disagree. He specifically talks about removing the zero time. Of course he is obviously unsure about how a DateTime works so anything is possible.
Kevin Gale
@Kevin Gale: Correct, any interpetation may fly, he is obviously new to the `DateTime` type. Therefore I contend my answer is useful. A downvote seems harsh.
codekaizen
@codekaizen: You're right it was a bit harsh. But neither did you provide any explanation that your response didn't really answer his question because the question doesn't make sense. If you are going to answer the question you think he is asking you should explain that.
Kevin Gale
+1  A: 

If you are asking if the DateTime object can be time-ignorant, the answer is no. You could create a user-defiened class of Date that just returns the Date portion of a DateTime object. If you are just looking to truncate the time, see below.

DateTime now = DateTime.Now;
DateTime today = now.Date;

or

DateTime now = DateTime.Now;
DateTime today = new DateTime(now.Year, now.Month, now.Day);
Brad
A: 

Can't you just take it from the DateTime object and then .ToString() it?

DateTime current = DateTime.Now;
string myTime = current.TimeOfDay.Tostring()

You might want to strip the milliseconds from the end...

dotalchemy
A: 

This can't be done. A DateTime always has a time even if the time is 00:00:00

You can only remove that when converting to a string.

Kevin Gale
A: 

As mentioned by some others

var now = DateTime.Now;
var today = now.Date;

is the preffered way. However, since I like the timtowtdi philosophi:

var now = DateTime.Now;
var today = now.Add(-now.TimeOfDay);
SchlaWiener
A: 

You can Trim a Date to Hours Minutes, Day ..

 DateTime t = DateTime.Now;
 DateTime t2 = t - new TimeSpan(t.Ticks % TimeSpan.TicksPerDay);

You can use also TicksPerHour, TicksPerMinute and TicksPerSecond.

x77