关于区域日期C#代码

//有时候区域时间设定与程序不配,导致日期字符处理出错,研究了很久,查阅微软参数,终于得到这些心得,可以在程序中任意采用自定义日期格式
//笨办法获得yy/MM/dd HH:mm格式时间:
// CountDateStr = CountDate.Year.ToString().Substring(CountDate.Year.ToString().Length - 2, 2) + "/" + CountDate.Month.ToString("00") + "/" + CountDate.Day.ToString("00") + " " + CountDate.ToString("HH:mm"); //取得缺失段次的时间//笨办法
//
// CountDateStr = CountDate.ToString("yy/MM/dd HH:mm");                 //系统日期格式如果是yyyy-MM-dd,无法用此转换格式到yy/MM/dd
// CountDateStr = String.Format("{0:yy/MM/dd HH:mm}", CountDate);       //系统日期格式如果是yyyy-MM-dd,无法用此转换格式到yy/MM/dd

using System.Globalization;//在文件头加入此命名空间。

       private void button4_Click(object sender, EventArgs e)//命令按钮4
        {
            string[] DateTimeTypes = { "d", "D", "f", "F", "g", "G", "m", "M", "o", "O", "r", "R", "s", "t" , "u", "U", "y", "Y" };//时间类型
            string[] LanguagesTypes = { "", "zh-CN", "en-US", "en", "en-GB", "fr", "fr-FR", "de", "de-DE"};//区域语言类型
             //"en-US"英语-美国,"en-GB"英语-英国,"fr"法语,"fr-FR"法语-法国,"en"英语,"zh-CN","de"德语,"de-DE"德语德国

            foreach (string Ltype in LanguagesTypes)
            {
                foreach (string Dtype in DateTimeTypes)
                {
                    Console.WriteLine(string.Format("{0} {1}:{2}", Ltype, Dtype.PadLeft(3, ' '), DateTime.Now.ToString(Dtype, CultureInfo.CreateSpecificCulture(Ltype))));
                }
            }
           //最优选方法:
            CultureInfo cul = CultureInfo.CreateSpecificCulture("");//创建固定区域信息
            DateTimeFormatInfo DTFI = cul.DateTimeFormat;//获得创建的时间格式信息
                                                         // DTFI.DateSeparator = "/";//指定分隔符可以不使用
            Console.WriteLine(DateTime.Now.ToString("yy.MM.dd HH:mm", DTFI));//输出自定义格式日期时间
            Console.WriteLine(DateTime.Now.ToString("yy/MM/dd HH:mm", DTFI));//输出自定义格式日期时间
            Console.WriteLine(DateTime.Now.ToString("yy-MM-dd HH:mm", DTFI));//输出自定义格式日期时间
           //整理人:zyyujq
        }

猜你喜欢

转载自blog.csdn.net/zyyujq/article/details/89532158