in

Alex's TechBoard

log technical notes, Share skills&tricks&knowledge, communicate each other.

Techpad

Functions that Convert unix timestamp to datetime or datetime to unix timestamp in C#

[this code segment was partly copy from somewhere else, Not my own article] 

         public long DateTime2UnixTimeStamp(DateTime dt)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            DateTime dtNow = DateTime.Parse(dt.ToString());
            TimeSpan toNow = dtNow.Subtract(dtStart);
            string timeStamp = toNow.Ticks.ToString();
            timeStamp = timeStamp.Substring(0, timeStamp.Length - 7);

            return Convert.ToInt64(timeStamp);
        }

        public DateTime UnixTimeStamp2DateTime(long uts)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(uts.ToString() + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);

            return dtResult;
        }

Published Aug 30 2007, 02:33 PM by lidou
Filed under: , , , , ,

Comments

No Comments
Copyright cookrss.com 2007
Powered by Community Server (Commercial Edition), by Telligent Systems