【C#】淺析C#中的日期處理

來源:互聯網
上載者:User

標籤:bsp   需要   pattern   test   限制   datetime   重載   oba   轉化   

1.字串轉化為日期1.1第一種方式

使用 Convert.toDateTime 方法,該方法有很多重載方法,這裡筆者就介紹兩個常用的重載方法。

第一種:

使用:

Convert.ToDateTime(string)

使用該方法轉化有一個限制,就是字串的格式應該類似為“yyyy-MM-dd hh:mm:ss”的,比如:“2017-12-12 00:01:11”。剛才為什麼說應該類似為“yyyy-MM-dd hh:mm:ss”的格式呢,因為像這種格式“2017/12/12 00:01:11”,它也能識別。該方法還可以轉化null值,null將會轉化為“1/1/0001 12:00:00”,不過該方法支援的形勢有限。使用下面這種方法,靈活性要強一些,

第二種:

Convert.ToDateTime(string, IFormatProvider)

例如:

DateTime dt;DateTimeFormatInfo dtFormat = new System.GlobalizationDateTimeFormatInfo();dtFormat.ShortDatePattern = "yyyy/MM/dd";dt = Convert.ToDateTime("2011/05/26", dtFormat);
1.2第二種方式

使用 DateTime.ParseExact 使用該方法,也可以達到把字串轉化日期的目的,該方法也有重載方法,這裡筆者介紹一種:

ParseExact(String, String, IFormatProvider)

接下來就可以使用了

string dateString = "20110526";DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

或是:

DateTime dt = DateTime.ParseExact(dateString, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture);
2.日期轉化為字串2.1第一種方式

如果日期需要轉化為字串,那麼直接使用 ToString() 方法,就可以了。

比如:

DateTime dt = DateTime.Now;String res = dt.ToString("yyyy年MM月dd HH時mm分ss秒");

下面給出一些日期格式標識符

yyyy:代表年份
MM:  代表月份
dd:  代表天
HH:  代表小時(24小時制)
hh:   代表小時(12小時制)
mm:  代表分鐘
ss:  代表秒

【C#】淺析C#中的日期處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.