Convert DateTime to Int

c#, datetime, int, sql, sql-server

Solution

I don't understand why you would need to represent a `DateTime` as an integer in C#, but you can use this method:

public static int DateTimeToInt(DateTime theDate)
{
    return (int)(theDate.Date - new DateTime(1900, 1, 1)).TotalDays + 2;
}

And you can use this method for the reverse operation:

public static DateTime IntToDateTime(int intDate)
{
    return new DateTime(1900, 1, 1).AddDays(intDate - 2);
}

Problem

This is the sample I did in SQL Server ``` SELECT CAST(CAST('2012-01-25 10:00:00.000' AS DATETIME) AS INT) + 2 ``` Result is 40933 How can I achieve this using c#? From where and how this integer comes? Reference: Convert from DateTime to INT but this is what I need in c#

Original source

Related problems