How can I convert a DateTime to an int?
I have the following DateTime 4/25/2011 5:12:13 PM and tried this to convert it to int
int result = dateDate.Year * 10000 + dateDate.Month * 100
+ dateDate.Day + dateDate.Hour + dateDate.Minute + dateDate.Second;
But it still getting 2011425 how can i get the time as well?
dateDate.Ticks
should give you what you're looking for.
The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.
DateTime.Ticks
If you're really looking for the Linux Epoch time (seconds since Jan 1, 1970), the accepted answer for this question should be relevant.
But if you're actually trying to "compress" a string representation of the date into an int, you should ask yourself why aren't you just storing it as a string to begin with. If you still want to do it after that, Stecya's answer is the right one. Keep in mind it won't fit into an int, you'll have to use a long.
long n = long.Parse(date.ToString("yyyyMMddHHmmss"));
see Custom Date and Time Format Strings
I think you want (this won't fit in a int
though, you'll need to store it as a long
):
long result = dateDate.Year * 10000000000 + dateDate.Month * 100000000 + dateDate.Day * 1000000 + dateDate.Hour * 10000 + dateDate.Minute * 100 + dateDate.Second;
Alternatively, storing the ticks is a better idea.
Do you want an 'int' that looks like 20110425171213? In which case you'd be better off ToString with the appropriate format (something like 'yyyyMMddHHmmss') and then casting the string to an integer (or a long, unsigned int as it will be way more than 32 bits).
If you want an actual numeric value (the number of seconds since the year 0) then that's a very different calculation, e.g.
result = second
result += minute * 60
result += hour * 60 * 60
result += day * 60 * 60 * 24
etc.
But you'd be better off using Ticks.