鸟语天空
将字符串转换为DateTime
post by:追风剑情 2016-4-14 14:54

时间字符串与DateTime

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringToDateTimeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("当前时间: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt 时区z"));

            //美国: 月份/日期/年份
            string date = "01/08/2008";
            Console.WriteLine("字符串"+date);
            DateTime dt = Convert.ToDateTime(date);
            Console.WriteLine("美国 Year: {0}, Month: {1}, Day: {2}", dt.Year, dt.Month, dt.Day);

            //法国: 日期/月份/年份
            IFormatProvider culture = new System.Globalization.CultureInfo("fr-FR", true);//本地化
            DateTime dt2 = DateTime.Parse(date, culture, System.Globalization.DateTimeStyles.AssumeLocal);
            Console.WriteLine("法国 Year: {0}, Month: {1}, Day {2}", dt2.Year, dt2.Month, dt2.Day);
            Console.WriteLine();

            string dateString = null;

            Console.WriteLine("字符串null:");
            ConvertToDateTime(dateString);

            Console.WriteLine("字符串empty:");
            dateString = String.Empty;
            ConvertToDateTime(dateString);

            Console.WriteLine("字符串not-date:");
            dateString = "not a date";
            ConvertToDateTime(dateString);

            // Try to convert various date strings.
            Console.WriteLine("------------ 转换不同格式的时间字符串 -----------");
            dateString = "05/01/1996";
            ConvertToDateTime(dateString);
            dateString = "Tue Apr 28, 2009";
            ConvertToDateTime(dateString);
            dateString = "Wed Apr 28, 2009";
            ConvertToDateTime(dateString);
            dateString = "06 July 2008 7:32:47 AM";
            ConvertToDateTime(dateString);
            dateString = "17:32:47.003";
            ConvertToDateTime(dateString);
            // Convert a string returned by DateTime.ToString("R").
            dateString = "Sat, 10 May 2008 14:32:17 GMT";
            ConvertToDateTime(dateString);
            // Convert a string returned by DateTime.ToString("o").
            dateString = "2009-05-01T07:54:59.9843750-04:00";
            ConvertToDateTime(dateString);


            Console.Read();
        }

        private static void ConvertToDateTime(string value)
        {
            DateTime convertedDate;
            try
            {
                convertedDate = Convert.ToDateTime(value);
                Console.WriteLine("字符串{0}\n   {1}\n   Kind: {2}",
                                  value, convertedDate,
                                  convertedDate.Kind.ToString());
            }
            catch (FormatException)
            {
                Console.WriteLine("'{0}' is not in the proper format.", value);
            }
        }
    }
}

 

运行结果

111111.png

 

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容