Baran Topal

Baran Topal


October 2024
M T W T F S S
« Feb    
 123456
78910111213
14151617181920
21222324252627
28293031  

Categories


size/length of DateTime and truncation of DateTime to 8 bytes

baranbaran

I found this code in my backups and apparently, I needed to truncate C# DateTime at some time. Probably, it wasn’t a good idea from the start but maybe, there was a last resort scenario. Here you go:


class Program
{
	static void Main(string[] args)
	{
		DateTime dt = DateTime.Now;
		long time_t = DateTimeToTimeT(dt);

		Console.WriteLine("Current time_t: {0}", time_t);

		Console.ReadKey();
	}

	static long DateTimeToTimeT(DateTime time)
	{
		DateTime epoch = new DateTime(1970, 1, 1, 00, 00, 00, DateTimeKind.Utc);
		DateTime d = epoch.ToLocalTime();
		if (time.Kind == DateTimeKind.Local)
			return (long)(time.ToUniversalTime() - epoch).TotalSeconds;
		else
			return (long)(time - epoch).TotalSeconds;
	}

}

I also found this Knowledge Base article: http://support.microsoft.com/kb/167296/. That article describes going from a time_t to a FILETIME.


class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("Current time_t: {0}",
			FileTimeToUnixTime(DateTime.Now.ToFileTime()));
		Console.ReadKey();
	}

	static long FileTimeToUnixTime(long filetime)
	{
		return (filetime / 10000000) - 11644473600;
	}

}