How can I convert a DateTime to an int?

C#Datetime

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

long n = long.Parse(date.ToString("yyyyMMddHHmmss"));

see Custom Date and Time Format Strings

Solution 3 - C#

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.

Solution 4 - C#

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.

Solution 5 - C#

string date = DateTime.Now.ToString();

date = date.Replace("/", "");
date = date.Replace(":", "");
date = date.Replace(" ", "");
date = date.Replace("AM", "");
date = date.Replace("PM", "");            
return date;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsomeguyView Question on Stackoverflow
Solution 1 - C#Alex JView Answer on Stackoverflow
Solution 2 - C#StecyaView Answer on Stackoverflow
Solution 3 - C#Jackson PopeView Answer on Stackoverflow
Solution 4 - C#UnslicedView Answer on Stackoverflow
Solution 5 - C#l1k0pl4st1View Answer on Stackoverflow