Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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;
        }

Friday, June 19, 2009

C# How to convert byte arry to string

0 comments
Scenario
How to a byte array to a string? The solution is using the 'GetString()' method from the ASCIIEncoding.ASCII object. Be carrefull with this method, it may cause problems if you try to convert something other than English, such as Chinese and other asian languages. In this case, you have to use specific ASCII encoding for that language.
For example, you probably want to use System.Text.Encoding.GetEncoding(1251).GetString(b);
Here, '1251' stands for English. You can choose your own codepage for Encoding or Decoding.

Method
byte[] data = ... ; //whatever it is here
string text1 = System.Text.ASCIIEncoding.ASCII.GetString(data);//Let the ASCIIEncoding handle the convertion
string text2 = System.Text.Encoding.GetEncoding(1251).GetString(data);// 1251 stands for English
string text3 = System.Text.Encoding.GetEncoding(28591).GetString(data);// 28591 stands for Latin
string text4 = System.Text.Encoding.GetEncoding("GB18030").GetString(data);// "GB18030" stands for Simplified Chinese

BlogUpp!

 

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