Json 的日期格式與.Net DateTime型別的轉換

wl1121發表於2009-05-30

 static void Main(string[] args)
        { 
            string [] jsonDates = {"/Date(1242357713797+0800)/" , "/Date(1242357722890+0800)/"};
            foreach (string jsonDate in jsonDates)
            {
                Console.WriteLine("Json : {0}", jsonDate);
                DateTime  dtResult =   JsonToDateTime(jsonDate);
                Console.WriteLine("DateTime: {0}", dtResult.ToString("yyyy-MM-dd hh:mm:ss ffffff"));
            } 
            Console.Read();
        }

        public static DateTime JsonToDateTime(string jsonDate)
        {
            string value = jsonDate.Substring(6, jsonDate.Length - 8);
            DateTimeKind kind = DateTimeKind.Utc;
            int index = value.IndexOf('+', 1);
            if (index == -1)
                index = value.IndexOf('-', 1);
            if (index != -1)
            {
                kind = DateTimeKind.Local;
                value = value.Substring(0, index);
            }
            long javaScriptTicks = long.Parse(value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture);
            long InitialJavaScriptDateTicks = (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;
            DateTime utcDateTime = new DateTime((javaScriptTicks * 10000) + InitialJavaScriptDateTicks, DateTimeKind.Utc);
            DateTime dateTime;
            switch (kind)
            {
                case DateTimeKind.Unspecified:
                    dateTime = DateTime.SpecifyKind(utcDateTime.ToLocalTime(), DateTimeKind.Unspecified);
                    break;
                case DateTimeKind.Local:
                    dateTime = utcDateTime.ToLocalTime();
                    break;
                default:
                    dateTime = utcDateTime;
                    break;
            }
            return dateTime ;
        }
 
 

相關文章