Friday, February 5, 2010

C# Convert time to seconds since Jan 1, 2000

0 comments
Scenario
We know that the build-in DateTime object provide us a very convenience way to manipulate the number of seconds of time.  However, for hardware device, there might be a limit with the buffer during the transmission.  The DateTime starts counting the time since Jan 1, 0000.  We will have 63082281600000000000 nanoseconds until Jan 1, 2000.  For most of cases, we are not interested in any data between year 0000 and year 2000.  Therefore, the following methods just give an alternative way to calculate and convert the number of seconds from DateTime object.

Method 
        // Since 12:00:00 am Jan 1, 2000
        public const long INITIAL_DATETIME = 630822816000000000;

        // Convert current time to number of seconds since Jan 1, 2000.
        public static int GetTimeForDevice()
        {
            int ans = 0;

            ans = (int)((DateTime.Now.Ticks - INITIAL_DATETIME) / 10000000);

            return ans;
        }

        // Convert time from number of seconds since Jan 1, 2000 to a readable string
        public static string GetTimeFromDevice(string time)
        {
            string ans = "";

            long temp = Int32.Parse(time) * 10000000 + INITIAL_DATETIME;
            DateTime dt = new DateTime(temp);
            ans = dt.ToShortDateString() + " " + dt.ToLongTimeString();

            return ans;
        }

BlogUpp!

 

Copyright 2009 All Rights Reserved Revolution Two Lifestyle theme by Brian Gardner | Blogger template converted & enhanced by eBlog Templates