C# 时间与字符串类型的相互格式化转换


以下这第一部分是来自网络,基本也都是对的。可以参考着用。

哎~~哎,别急着关,再往下看看

时间格式化输出:
     Label1.Text = dt.ToString();//2005-11-5 13:21:25
       Label2.Text = dt.ToFileTime().ToString();//127756416859912816
       Label3.Text = dt.ToFileTimeUtc().ToString();//127756704859912816
       Label4.Text = dt.ToLocalTime().ToString();//2005-11-5 21:21:25
       Label5.Text = dt.ToLongDateString().ToString();//2005年11月5日
     Label6.Text = dt.ToLongTimeString().ToString();//13:21:25
       Label7.Text = dt.ToOADate().ToString();//38661.5565508218
       Label8.Text = dt.ToShortDateString().ToString();//2005-11-5
       Label9.Text = dt.ToShortTimeString().ToString();//13:21
       Label10.Text = dt.ToUniversalTime().ToString();//2005-11-5 5:21:25  2005-11-5 13:30:28.4412864
       Label1.Text = dt.Year.ToString();//2005
       Label2.Text = dt.Date.ToString();//2005-11-5 0:00:00
       Label3.Text = dt.DayOfWeek.ToString();//Saturday
       Label4.Text = dt.DayOfYear.ToString();//309
       Label5.Text = dt.Hour.ToString();//13
       Label6.Text = dt.Millisecond.ToString();//441
       Label7.Text = dt.Minute.ToString();//30
       Label8.Text = dt.Month.ToString();//11
       Label9.Text = dt.Second.ToString();//28
       Label10.Text = dt.Ticks.ToString();//632667942284412864
       Label11.Text = dt.TimeOfDay.ToString();//13:30:28.4412864
       Label1.Text = dt.ToString();//2005-11-5 13:47:04
       Label2.Text = dt.AddYears(1).ToString();//2006-11-5 13:47:04
       Label3.Text = dt.AddDays(1.1).ToString();//2005-11-6 16:11:04
       Label4.Text = dt.AddHours(1.1).ToString();//2005-11-5 14:53:04
       Label5.Text = dt.AddMilliseconds(1.1).ToString();//2005-11-5 13:47:04
       Label6.Text = dt.AddMonths(1).ToString();//2005-12-5 13:47:04
       Label7.Text = dt.AddSeconds(1.1).ToString();//2005-11-5 13:47:05
       Label8.Text = dt.AddMinutes(1.1).ToString();//2005-11-5 13:48:10
       Label9.Text = dt.AddTicks(1000).ToString();//2005-11-5 13:47:04
       Label10.Text = dt.CompareTo(dt).ToString();//0
       Label11.Text = dt.Add(?).ToString();//问号为一个时间段
       Label1.Text = dt.Equals("2005-11-6 16:11:04").ToString();//False
       Label2.Text = dt.Equals(dt).ToString();//True
       Label3.Text = dt.GetHashCode().ToString();//1474088234
       Label4.Text = dt.GetType().ToString();//System.DateTime
       Label5.Text = dt.GetTypeCode().ToString();//DateTime

       Label1.Text = dt.GetDateTimeFormats('s')[0].ToString();//2005-11-05T14:06:25
       Label2.Text = dt.GetDateTimeFormats('t')[0].ToString();//14:06
       Label3.Text = dt.GetDateTimeFormats('y')[0].ToString();//2005年11月
     Label4.Text = dt.GetDateTimeFormats('D')[0].ToString();//2005年11月5日
     Label5.Text = dt.GetDateTimeFormats('D')[1].ToString();//2005 11 05
       Label6.Text = dt.GetDateTimeFormats('D')[2].ToString();//星期六 2005 11 05
       Label7.Text = dt.GetDateTimeFormats('D')[3].ToString();//星期六 2005年11月5日
     Label8.Text = dt.GetDateTimeFormats('M')[0].ToString();//11月5日
     Label9.Text = dt.GetDateTimeFormats('f')[0].ToString();//2005年11月5日 14:06
       Label10.Text = dt.GetDateTimeFormats('g')[0].ToString();//2005-11-5 14:06
       Label11.Text = dt.GetDateTimeFormats('r')[0].ToString();//Sat, 05 Nov 2005 14:06:25 GMTv 
=================================================

1.DateTime.Parse(str);
2.DateTime dt = DateTime.Now;
   DateTime.TryParse(str,out dt);
3.Convert.ToDateTime(str);

1.直接强转,如果转换过程有异常将会抛出异常,否则返回转换后的结构。
2.先创建一个DateTime对象,如果有异常,返回值将是dt创建时候的值,如果没异常,会把转换后的结果赋给dt。
3.也是直接强转,如果转换过程有异常将会抛出异常,否则返回转换后的结构。与1的区别就是,它能接受的参数类型更多。

 

----------------------------------------我是分割线---------------------------------

 

首先我们先看一段MSDN的示例代码,它对日期的一些样式设置做了简单示例。

using System;
using System.Globalization;


public class SamplesCultureInfo  {

   public static void Main()  {

      // Creates and initializes a CultureInfo.
      CultureInfo myCI = new CultureInfo("en-US", false);

      // Clones myCI and modifies the DTFI and NFI instances associated with the clone.
      CultureInfo myCIclone = (CultureInfo) myCI.Clone();
      myCIclone.DateTimeFormat.AMDesignator = "a.m.";
      myCIclone.DateTimeFormat.DateSeparator = "-";
      myCIclone.NumberFormat.CurrencySymbol = "USD";
      myCIclone.NumberFormat.NumberDecimalDigits = 4;

      // Displays the properties of the DTFI and NFI instances associated with the original and with the clone. 
      Console.WriteLine( "DTFI/NFI PROPERTY\tORIGINAL\tMODIFIED CLONE" );
      Console.WriteLine( "DTFI.AMDesignator\t{0}\t\t{1}", myCI.DateTimeFormat.AMDesignator, myCIclone.DateTimeFormat.AMDesignator );
      Console.WriteLine( "DTFI.DateSeparator\t{0}\t\t{1}", myCI.DateTimeFormat.DateSeparator, myCIclone.DateTimeFormat.DateSeparator );
      Console.WriteLine( "NFI.CurrencySymbol\t{0}\t\t{1}", myCI.NumberFormat.CurrencySymbol, myCIclone.NumberFormat.CurrencySymbol );
      Console.WriteLine( "NFI.NumberDecimalDigits\t{0}\t\t{1}", myCI.NumberFormat.NumberDecimalDigits, myCIclone.NumberFormat.NumberDecimalDigits );

   }

}

/*
This code produces the following output.

DTFI/NFI PROPERTY       ORIGINAL        MODIFIED CLONE
DTFI.AMDesignator       AM              a.m.
DTFI.DateSeparator      /               -
NFI.CurrencySymbol      $               USD
NFI.NumberDecimalDigits 2               4

*/


就是说,我们可以通过System.Globalization.CultureInfo类,对日期的格式化转换输出做出设定。

所以,当我把代码改成这样时:

//记得 using System.Globalization;

// Creates and initializes a CultureInfo.
            CultureInfo myCI = new CultureInfo("en-US", false);

            // Clones myCI and modifies the DTFI and NFI instances associated with the clone.
            CultureInfo myCIclone = (CultureInfo)myCI.Clone();
            myCIclone.DateTimeFormat.AMDesignator = "a.m.";
            myCIclone.DateTimeFormat.PMDesignator = "P.M.";
            myCIclone.DateTimeFormat.DateSeparator = ".";
            myCIclone.NumberFormat.CurrencySymbol = "USD";
            myCIclone.NumberFormat.NumberDecimalDigits = 4;

            // Displays the properties of the DTFI and NFI instances associated with the original and with the clone. 
            Console.WriteLine("DTFI/NFI PROPERTY\tORIGINAL\tMODIFIED CLONE");
            Console.WriteLine("DTFI.AMDesignator\t{0}\t\t{1}", myCI.DateTimeFormat.AMDesignator, myCIclone.DateTimeFormat.AMDesignator);
            Console.WriteLine("DTFI.DateSeparator\t{0}\t\t{1}", myCI.DateTimeFormat.DateSeparator, myCIclone.DateTimeFormat.DateSeparator);
            Console.WriteLine("NFI.CurrencySymbol\t{0}\t\t{1}", myCI.NumberFormat.CurrencySymbol, myCIclone.NumberFormat.CurrencySymbol);
            Console.WriteLine("NFI.NumberDecimalDigits\t{0}\t\t{1}", myCI.NumberFormat.NumberDecimalDigits, myCIclone.NumberFormat.NumberDecimalDigits);

            Console.WriteLine(DateTime.Now.ToString(myCIclone));

输出是:
DTFI/NFI PROPERTY       ORIGINAL        MODIFIED CLONE
DTFI.AMDesignator       AM              a.m.
DTFI.DateSeparator      /               .
NFI.CurrencySymbol      $               USD
NFI.NumberDecimalDigits 2               4
5.19.2013 12:18:44 a.m.

----------------------------

红色字部分是当前日期时间,也就是我写这篇文章的时间了。

表示早晨的“AM”改成了“a.m.”,而我们习惯的yyyy-MM-dd格式中的“-”或者系统通常默认设置的“/”分隔符被我改成了“.”。

好吧。我们继续往下走。

我的主要目的是改日期时间格式,从上文示例中可以看出来,我们应该操作的就是DateTimeFormat中的设置了。

恰好,DateTimeFormat对应有一个类,其继承结构是: System.Globalization.DateTimeFormatInfo

接下来的问题就很简单了,直接简单粗暴的上一段代码:

System.Globalization.DateTimeFormatInfo fi = new System.Globalization.DateTimeFormatInfo();            
fi.FullDateTimePattern="yyyy年MM月dd日 的 HH时mm分ss秒";
Console.WriteLine("{0}", DateTime.Now.ToString(fi.FullDateTimePattern));

结果是这样的:2013年05月19日 的 00时18分44秒

当然,你也可以更粗暴的:

Console.WriteLine(DateTime.Now.ToString("yyyy年MM月dd日 的 HH时mm分ss秒"));

结果是一样的。

但我在示例中用的是全格式日期时间FullDateTimePattern,DateTimeFormatInfo还有很多其它的设置,灵活性更强一点。

具体请看MSDN:http://msdn.microsoft.com/zh-cn/library/system.globalization.datetimeformatinfo(v=vs.100).aspx

 

说完时间转字符串的,接着说说字符串转时间的。

 我们在处理字符串(string类型)转日期类型(DateTime)时常用DateTime.Pares() ,但如果在处理旧有特殊时间字符串数据的时候,如何转换成时间类型呢,例如

//分别获取20051126中的年、月、日字符串
string   yyyy= "20051126 ".Substring(0,4);
string   mm= "20051126 ".Substring(4,2);
string   dd= "20051126 ".Substring(5,2);

//拼写符合日期格式的字符串
string   riqi=yyyy+ "- "+mm+ "- "+dd;

//将符合日期格式的字符串转化为DateTime数据类型
DateTime   dt=Convert.ToDateTime(riqi);
DateTime dt = DateTime.Parse(str);


//但是这个形式的转换是相当有限的,有些C#是会不懂你写入的日期格式的如20100427140027
//大家都明白是2010-04-27 可以C#不认识他.我们可以这样子进行如下
string strDateFormat = "yyyyMMddHHmmss";
string date = "20100427140027";
DateTime convertTime = DateTime.ParseExact(date, strDateFormat, new System.Globalization.CultureInfo("zh-CN"), System.Globalization.DateTimeStyles.AllowWhiteSpaces);
Console.Write(string.Format("{0}", convertTime.ToString()));

//输出:2010-04-27 14:00:27

我们再改改

string strDateFormat = "yyyy年MM月dd日 的 HH时mm分ss秒"; 
string date = "2089年05月19日 的 23时49分23秒";
DateTime convertTime = DateTime.ParseExact(date, strDateFormat, new System.Globalization.CultureInfo("zh-CN"), System.Globalization.DateTimeStyles.AllowWhiteSpaces);
Console.WriteLine(string.Format("{0}", convertTime.ToString()));

输出:2089-05-19 23:49:23

 

文笔不好,但希望内容对您有帮助。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM