tags:

views:

527

answers:

9

I'm trying to store a shortened date (mm/dd/yyyy) into a DateTime object. The following code below is what I am currently trying to do; this includes the time (12:00:00 AM) which I do not want :(

DateTime goodDateHolder = Convert.ToDateTime(DateTime.Now.ToShortDateString());

Result will be 10/19/2009 12:00:00 AM

+2  A: 

Instead of .Now you can use .Today which will not remove the time part, but will only fill the date part and leave time to the default value.

Later on, as others pointed out, you should try to get the date part ignoring the time part, depending on the situation.

Petros
DateTime.Today.ToShortDateString() still has the time as 12:00:00 AM
mezoid
Yes, you are right. I provided more info.
Petros
+12  A: 

DateTime is an integer interpreted to represent both parts of DateTime (ie: date and time). You will always have both date and time in DateTime. Sorry, there's nothing you can do about it.

You can use .Date to get the date part. In these cases, the time will always be 12:00 but you can just ignore that part if you don't want it.

Dinah
+3  A: 

You only have two options in this situation.

1) Ignore the time part of the value.

2) Create a wrapper class.

Personally, I am inclined to use option 1.

ChaosPandion
+3  A: 

A DateTime will always have a time component - even if it is 12:00:00 AM. You just need to format the DateTime when you display it (e.g. goodDateHolder.ToShortDateString()).

TLiebe
A: 

DateTime object stores both the date and the time. To display only the date, you would use the DateTime.ToString(string) method.

DateTime goodDateHolder = DateTime.Now;
// outputs 10/19/2009
Console.WriteLine(goodDateHolder.ToString("MM/dd/yyyy"));

For more information on the ToString method, follow this link

Brandon
In most cases it's better to use ToShortDateString, so that the date component uses the localized format.
Meta-Knight
A: 

You might not be able to get it as a DateTime object...but when you want to display it you can format it in the way you want by doing something like.

myDateTime.ToString("M/d/yyyy") which gives 10/19/2009 for your example.

mezoid
A: 

You'll always get the time portion in a DateTime type.

DateTime goodDateHolder = Convert.ToDateTime(DateTime.Now.ToShortDateString());

will give you today's date but will always show the time to be midnight.

If you're worried about formatting then you would try something like this

goodDateHolder.ToString("mm/dd/yyyy")

to get the date in the format that you want.

This is a good resource msdn-dateformat

ilustreous
A: 

DateTime is merely a UInt64 with useful and clever formatting wrapped around it to make it appear like a date plus a time. You cannot eliminate the time element.

Violently Happy
+1  A: 

You can also check out Noda Time based off the Java Joda Time library.

Pete