views:

265

answers:

2

What is the quickest way to convert a DateTime to a int representation of the format yyyyMMdd.

i.e. 01-Jan-2007 --> 20070101 (as in int)?

+3  A: 
int result = int.Parse(myDate.ToString("yyyyMMdd"));
Reed Copsey
+1, I would just add you might want to do a TryParse, just to be safe.
Jack Marchetti
so it is required to first convert the DateTime to a string, then to an int? Thanks for your code, i was unaware of int.Parse
Phillis
@Phillis: No, it's not required. But above code shows better what exactly is going on, though.
Joey
@JackM - This would be a rare case where TryParse is unnecessary as there is no way the format string will ever result in a non-integer.
ebpower
Yes - here you KNOW the format, in advance, so it's safe to avoid. Johannes's answer is better, though.
Reed Copsey
+9  A: 
int x = date.Year * 10000 + date.Month * 100 + date.Day
Joey
+1 Creative solution to avoid parsing the string.
Steve Danner
@Steve: Well, the most straightforward that came to my mind ;). The format string variant just makes things a little clearer for someone only casually glancing at the code.
Joey
Nice option for this. Very clean way to handle it.
Reed Copsey