C#實(shí)現(xiàn)將字符串轉(zhuǎn)化為日期格式的方法詳解
在程序設(shè)計(jì)過程中,經(jīng)常需要顯示系統(tǒng)日期,使用DateTime結(jié)構(gòu)的Now屬性可以獲取系統(tǒng)的日期信息,此時(shí)調(diào)用ToString方法,將會(huì)返回日期的字符串表示,那么,怎樣將字符串轉(zhuǎn)換為日期格式呢?ParseExact方法可以輕松地實(shí)現(xiàn)此功能。
一、涉及到的知識(shí)點(diǎn)
1.ParseExact(String, String, IFormatProvider)
將日期和時(shí)間的指定字符串表示形式轉(zhuǎn)換為其等效的 DateTime。 字符串表示形式的格式必須與指定的格式完全匹配,否則會(huì)引發(fā)異常。
publie static DateTime ParseExact(string s,string format,IFormatProvider provider)
參數(shù)
s String 包含要轉(zhuǎn)換的日期和時(shí)間的字符串。
format String 用于定義所需的 s 格式的格式說明符。 有關(guān)詳細(xì)信息,請參閱“備注”部分。
provider IFormatProvider 一個(gè)對(duì)象,提供有關(guān) s 的區(qū)域性特定格式信息。
返回
DateTime 一個(gè)對(duì)象,它等效于 s 中包含的日期和時(shí)間,由 format 和 provider 指定。
ArgumentNullException
s 或 format 為 null。
FormatException
s 或 format 是一個(gè)空字符串。
或 -
s 不包含與 format 中指定的模式相對(duì)應(yīng)的日期和時(shí)間。
或 -
s 中的小時(shí)組件和 AM/PM 指示符不一致。
ParseExact方法中的參數(shù)說明如下表:
參 數(shù) | 描 述 |
s | 字符串對(duì)象,表示包含要轉(zhuǎn)換的日期和時(shí)間的字符串 |
format | 字符串對(duì)象,表示s的預(yù)期格式 |
provide | 實(shí)現(xiàn)IFormatProvider接口的對(duì)象,表示用于提供有關(guān)s的區(qū)域性特定格式信息的IFormatProvider |
DateTime | 方法返回DateTime對(duì)象,等效于由format和provider所指定的s中包含的日期和時(shí)間 |
2.DateTime.ToLongDateString 方法
將當(dāng)前 DateTime 對(duì)象的值轉(zhuǎn)換為其等效的長日期字符串表示形式。
public string ToLongDateString ();
返回
String 一個(gè)字符串,它包含當(dāng)前 DateTime 對(duì)象的長日期字符串表示形式。
// DateTime.ToLongDateString 方法 using System.Globalization; namespace _067_3 { class Sample { public static void Main() { // 初始化 DateTime 對(duì)象 Console.WriteLine("Initialize the DateTime object to Jan 28, 2024 22:23:15 PM.\n"); DateTime datetime = new(2024, 1, 28, 22, 23, 15); // 當(dāng)前區(qū)域 Console.WriteLine($"Current culture: \"{CultureInfo.CurrentCulture.Name}\"\n"); var dtFormat = CultureInfo.CurrentCulture.DateTimeFormat; // Display the long date pattern and string. Console.WriteLine($"Long date pattern: \"{dtFormat.LongDatePattern}\""); Console.WriteLine($"Long date string: \"{datetime.ToLongDateString()}\"\n"); // Display the long time pattern and string. Console.WriteLine($"Long time pattern: \"{dtFormat.LongTimePattern}\""); Console.WriteLine($"Long time string: \"{datetime.ToLongTimeString()}\"\n"); // Display the short date pattern and string. Console.WriteLine($"Short date pattern: \"{dtFormat.ShortDatePattern}\""); Console.WriteLine($"Short date string: \"{datetime.ToShortDateString()}\"\n"); // Display the short time pattern and string. Console.WriteLine($"Short time pattern: \"{dtFormat.ShortTimePattern}\""); Console.WriteLine($"Short time string: \"{datetime.ToShortTimeString()}\"\n"); } } } // 運(yùn)行結(jié)果: /* Initialize the DateTime object to Jan 28, 2024 22:23:15 PM. Current culture: "zh-CN" Long date pattern: "yyyy-MM-dd" Long date string: "2024-01-28" Long time pattern: "HH:mm:ss" Long time string: "22:23:15" Short date pattern: "yyyy-MM-dd" Short date string: "2024-01-28" Short time pattern: "H:mm" Short time string: "22:23" */
3.Parse(String)方法
使用當(dāng)前區(qū)域性的約定將日期和時(shí)間的字符串表示形式轉(zhuǎn)換為其 DateTime 等效的表示形式。
public static DateTime Parse (string s);
參數(shù)
s String 包含要轉(zhuǎn)換的日期和時(shí)間的字符串。 有關(guān)詳細(xì)信息,請參閱要分析的字符串。
返回
DateTime 一個(gè)對(duì)象,它等效于 s 中包含的日期和時(shí)間。
例外
ArgumentNullException
s 為 null。
FormatException
s 不包含日期和時(shí)間的有效字符串表示形式。
二、實(shí)例1:ParseExact方法
1.源碼
// 使用ParseExact方法將字符串轉(zhuǎn)化為日期格式 namespace _067 { public partial class Form1 : Form { private GroupBox? groupBox1; private Button? button1; private Label? label3; private Label? label2; private Label? label1; private TextBox? textBox3; private TextBox? textBox2; private TextBox? textBox1; public Form1() { InitializeComponent(); Load += Form1_Load; } private void Form1_Load(object? sender, EventArgs e) { // // label3 // label3 = new Label { AutoSize = true, Location = new Point(285, 37), Name = "label3", Size = new Size(20, 17), TabIndex = 5, Text = "日" }; // // label2 // label2 = new Label { AutoSize = true, Location = new Point(203, 37), Name = "label2", Size = new Size(20, 17), TabIndex = 4, Text = "月" }; // // textBox2 // textBox2 = new TextBox { Location = new Point(147, 31), Name = "textBox2", Size = new Size(50, 23), TabIndex = 1 }; // // textBox1 // textBox1 = new TextBox { Location = new Point(35, 31), Name = "textBox1", Size = new Size(80, 23), TabIndex = 0 }; // // label1 // label1 = new Label { AutoSize = true, Location = new Point(121, 37), Name = "label1", Size = new Size(20, 17), TabIndex = 3, Text = "年" }; // // textBox3 // textBox3 = new TextBox { Location = new Point(229, 31), Name = "textBox3", Size = new Size(50, 23), TabIndex = 2 }; // // button1 // button1 = new Button { Location = new Point(141, 81), Name = "button1", Size = new Size(75, 23), TabIndex = 0, Text = "轉(zhuǎn)為日期", UseVisualStyleBackColor = true }; button1.Click += Button1_Click; // // groupBox1 // groupBox1 = new GroupBox { Location = new Point(12, 12), Name = "groupBox1", Size = new Size(340, 63), TabIndex = 0, TabStop = false, Text = "輸入日期字符串" }; groupBox1.Controls.Add(label3); groupBox1.Controls.Add(label2); groupBox1.Controls.Add(textBox2); groupBox1.Controls.Add(textBox1); groupBox1.Controls.Add(label1); groupBox1.Controls.Add(textBox3); groupBox1.SuspendLayout(); // // Form1 // AutoScaleDimensions = new SizeF(7F, 17F); AutoScaleMode = AutoScaleMode.Font; ClientSize = new Size(364, 116); Controls.Add(button1); Controls.Add(groupBox1); Name = "Form1"; StartPosition = FormStartPosition.CenterScreen; Text = "用ParseExact方法將字符串轉(zhuǎn)為日期"; groupBox1.ResumeLayout(false); groupBox1.PerformLayout(); } /// <summary> /// 得到日期字符串 /// 將字符串轉(zhuǎn)換為日期格式 /// </summary> private void Button1_Click(object? sender, EventArgs e) { string str = string.Format("{0}/{1}/{2}",textBox1!.Text, textBox2!.Text, textBox3!.Text); DateTime datetime = DateTime.ParseExact(str, "yyyy/MM/dd", null); MessageBox.Show("輸入的日期為: "+ datetime.ToLongDateString(), "提示!"); } } }
2.生成效果
3.示例2
// ParseExact 方法 using System.Globalization; namespace _067_1 { public class Example { public static void Main() { string dateString, format; DateTime result; CultureInfo provider = CultureInfo.InvariantCulture; // 解析不變區(qū)域的日期值 dateString = "01/28/2024"; format = "d"; try { result = DateTime.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); } // 使用“d”格式解析月份中不帶前導(dǎo)零的日期值 // 不變區(qū)域的標(biāo)準(zhǔn)短日期模式需要兩位數(shù)的月份 // 否則拋出 FormatException dateString = "1/28/2024"; try { result = DateTime.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); } // 使用自定義說明符轉(zhuǎn)換日期和時(shí)間。 dateString = "Sun 28 Jan 2024 8:30 AM -06:00"; format = "ddd dd MMM yyyy h:mm tt zzz"; try { result = DateTime.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); } // 轉(zhuǎn)換帶偏移量的日期和時(shí)間,但沒有分鐘的偏移量時(shí), // “zzz”說明符需要以小時(shí)為單位前導(dǎo)零, // 否則拋出 FormatException // 這里有兩處錯(cuò)誤:1日不是Sun和06:00 dateString = "Sun 01 Jan 2024 8:30 AM -06"; try { result = DateTime.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); } dateString = "28/01/2024 08:45"; format = "g"; provider = new CultureInfo("fr-FR"); try { result = DateTime.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); } // 使用法語(法國)和不變區(qū)域轉(zhuǎn)換包含秒和毫秒的日期 dateString = "28/01/2024 08:30:15.006542"; format = "dd/MM/yyyy HH:mm:ss.ffffff"; try { result = DateTime.ParseExact(dateString, format, provider); Console.WriteLine("{0} converts to {1}.", dateString, result.ToString()); } catch (FormatException) { Console.WriteLine("{0} is not in the correct format.", dateString); } } } } // 運(yùn)行結(jié)果: /* 01/28/2024 converts to 2024-01-28 00:00:00. 1/28/2024 is not in the correct format. Sun 28 Jan 2024 8:30 AM -06:00 converts to 2024-01-28 22:30:00. Sun 01 Jan 2024 8:30 AM -06 is not in the correct format. 28/01/2024 08:45 converts to 2024-01-28 08:45:00. 28/01/2024 08:30:15.006542 converts to 2024-01-28 08:30:15. */
三、實(shí)例2:Parse方法
// 以Parse(String)方法轉(zhuǎn)換多個(gè)日期和時(shí)間值的字符串表示形式 using System.Globalization; namespace _067_2 { public class DateTimeParser { public static void Main() { DateTime dateValue; string datetime = "1/28/2024 12:15:12 PM"; try { dateValue = DateTime.Parse(datetime); Console.WriteLine("'{0}' converted to {1}.", datetime, dateValue); } catch (FormatException) { Console.WriteLine("Unable to convert '{0}'.", datetime); } // Reverse month and day to conform to the fr-FR culture. // The date is February 16, 2008, 12 hours, 15 minutes and 12 seconds. datetime = "28/01/2024 12:35:20"; //正確順序01/28/2024 try { dateValue = DateTime.Parse(datetime); Console.WriteLine("'{0}' converted to {1}.", datetime, dateValue); } catch (FormatException) { Console.WriteLine("Unable to convert '{0}'.", datetime); } // formatted according to conventions of zh-HK Chinese - Hong Kong SAR culture. // 沒有zh-CN Chinese - China和zh-CHS Chinese (Simplified) , Neutral try { dateValue = DateTime.Parse(datetime, new CultureInfo("zh-HK", false)); Console.WriteLine("'{0}' converted to {1}.", datetime, dateValue); } catch (FormatException) { Console.WriteLine("Unable to convert '{0}'.", datetime); } // 轉(zhuǎn)換字符串型日期,不包含時(shí)間 datetime = "1/28/2024"; try { dateValue = DateTime.Parse(datetime); Console.WriteLine("'{0}' converted to {1}.", datetime, dateValue); } catch (FormatException) { Console.WriteLine("Unable to convert '{0}'.", datetime); } } } } //運(yùn)行結(jié)果: /* '1/28/2024 12:15:12 PM' converted to 2024-01-28 12:15:12. Unable to convert '28/01/2024 12:35:20'. '28/01/2024 12:35:20' converted to 2024-01-28 12:35:20. '1/28/2024' converted to 2024-01-28 00:00:00. */
到此這篇關(guān)于C#實(shí)現(xiàn)將字符串轉(zhuǎn)化為日期格式的方法詳解的文章就介紹到這了,更多相關(guān)C#字符串轉(zhuǎn)日期格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)導(dǎo)入CSV文件到Excel工作簿的方法
這篇文章主要介紹了C#實(shí)現(xiàn)導(dǎo)入CSV文件到Excel工作簿的方法,涉及C#針對(duì)office組件的相關(guān)操作技巧,需要的朋友可以參考下2015-06-06C# SynchronizationContext以及Send和Post使用解讀
這篇文章主要介紹了C# SynchronizationContext以及Send和Post使用解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05C#原型模式之如何通過克隆對(duì)象來優(yōu)化創(chuàng)建過程
原型模式是一種創(chuàng)建型設(shè)計(jì)模式,通過克隆現(xiàn)有對(duì)象來創(chuàng)建新對(duì)象,避免重復(fù)的創(chuàng)建成本和復(fù)雜的初始化過程,它適用于對(duì)象創(chuàng)建過程復(fù)雜、需要大量相似對(duì)象或避免重復(fù)初始化的場景,本文介紹C#原型模式之如何通過克隆對(duì)象來優(yōu)化創(chuàng)建過程,感興趣的朋友一起看看吧2025-03-03C# Dynamic之:ExpandoObject,DynamicObject,DynamicMetaOb的應(yīng)用(下)
本篇文章是對(duì)C#中ExpandoObject,DynamicObject,DynamicMetaOb的應(yīng)用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05C#.net編程創(chuàng)建Access文件和Excel文件的方法詳解
這篇文章主要介紹了C#.net編程創(chuàng)建Access文件和Excel文件的方法,結(jié)合實(shí)例形式總結(jié)分析了C#創(chuàng)建Access與Excel文件的幾種常用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06C#實(shí)現(xiàn)讓窗體永遠(yuǎn)在窗體最前面顯示的實(shí)例
這篇文章主要介紹了C#實(shí)現(xiàn)讓窗體永遠(yuǎn)在窗體最前面顯示,功能非常實(shí)用,需要的朋友可以參考下2014-07-07