C#實現(xiàn)將字符串轉(zhuǎn)化為日期格式的方法詳解
在程序設計過程中,經(jīng)常需要顯示系統(tǒng)日期,使用DateTime結(jié)構的Now屬性可以獲取系統(tǒng)的日期信息,此時調(diào)用ToString方法,將會返回日期的字符串表示,那么,怎樣將字符串轉(zhuǎn)換為日期格式呢?ParseExact方法可以輕松地實現(xiàn)此功能。
一、涉及到的知識點
1.ParseExact(String, String, IFormatProvider)
將日期和時間的指定字符串表示形式轉(zhuǎn)換為其等效的 DateTime。 字符串表示形式的格式必須與指定的格式完全匹配,否則會引發(fā)異常。
publie static DateTime ParseExact(string s,string format,IFormatProvider provider)
參數(shù)
s String 包含要轉(zhuǎn)換的日期和時間的字符串。
format String 用于定義所需的 s 格式的格式說明符。 有關詳細信息,請參閱“備注”部分。
provider IFormatProvider 一個對象,提供有關 s 的區(qū)域性特定格式信息。
返回
DateTime 一個對象,它等效于 s 中包含的日期和時間,由 format 和 provider 指定。
ArgumentNullException
s 或 format 為 null。
FormatException
s 或 format 是一個空字符串。
或 -
s 不包含與 format 中指定的模式相對應的日期和時間。
或 -
s 中的小時組件和 AM/PM 指示符不一致。
ParseExact方法中的參數(shù)說明如下表:
| 參 數(shù) | 描 述 |
| s | 字符串對象,表示包含要轉(zhuǎn)換的日期和時間的字符串 |
| format | 字符串對象,表示s的預期格式 |
| provide | 實現(xiàn)IFormatProvider接口的對象,表示用于提供有關s的區(qū)域性特定格式信息的IFormatProvider |
| DateTime | 方法返回DateTime對象,等效于由format和provider所指定的s中包含的日期和時間 |
2.DateTime.ToLongDateString 方法
將當前 DateTime 對象的值轉(zhuǎn)換為其等效的長日期字符串表示形式。
public string ToLongDateString ();
返回
String 一個字符串,它包含當前 DateTime 對象的長日期字符串表示形式。
// DateTime.ToLongDateString 方法
using System.Globalization;
namespace _067_3
{
class Sample
{
public static void Main()
{
// 初始化 DateTime 對象
Console.WriteLine("Initialize the DateTime object to Jan 28, 2024 22:23:15 PM.\n");
DateTime datetime = new(2024, 1, 28, 22, 23, 15);
// 當前區(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");
}
}
}
// 運行結(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)方法
使用當前區(qū)域性的約定將日期和時間的字符串表示形式轉(zhuǎn)換為其 DateTime 等效的表示形式。
public static DateTime Parse (string s);
參數(shù)
s String 包含要轉(zhuǎn)換的日期和時間的字符串。 有關詳細信息,請參閱要分析的字符串。
返回
DateTime 一個對象,它等效于 s 中包含的日期和時間。
例外
ArgumentNullException
s 為 null。
FormatException
s 不包含日期和時間的有效字符串表示形式。
二、實例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”格式解析月份中不帶前導零的日期值
// 不變區(qū)域的標準短日期模式需要兩位數(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)換日期和時間。
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)換帶偏移量的日期和時間,但沒有分鐘的偏移量時,
// “zzz”說明符需要以小時為單位前導零,
// 否則拋出 FormatException
// 這里有兩處錯誤: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);
}
}
}
}
// 運行結(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.
*/三、實例2:Parse方法
// 以Parse(String)方法轉(zhuǎn)換多個日期和時間值的字符串表示形式
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)換字符串型日期,不包含時間
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);
}
}
}
}
//運行結(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.
*/到此這篇關于C#實現(xiàn)將字符串轉(zhuǎn)化為日期格式的方法詳解的文章就介紹到這了,更多相關C#字符串轉(zhuǎn)日期格式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# SynchronizationContext以及Send和Post使用解讀
這篇文章主要介紹了C# SynchronizationContext以及Send和Post使用解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
C#原型模式之如何通過克隆對象來優(yōu)化創(chuàng)建過程
原型模式是一種創(chuàng)建型設計模式,通過克隆現(xiàn)有對象來創(chuàng)建新對象,避免重復的創(chuàng)建成本和復雜的初始化過程,它適用于對象創(chuàng)建過程復雜、需要大量相似對象或避免重復初始化的場景,本文介紹C#原型模式之如何通過克隆對象來優(yōu)化創(chuàng)建過程,感興趣的朋友一起看看吧2025-03-03
C# Dynamic之:ExpandoObject,DynamicObject,DynamicMetaOb的應用(下)
本篇文章是對C#中ExpandoObject,DynamicObject,DynamicMetaOb的應用進行了詳細的分析介紹,需要的朋友參考下2013-05-05
C#.net編程創(chuàng)建Access文件和Excel文件的方法詳解
這篇文章主要介紹了C#.net編程創(chuàng)建Access文件和Excel文件的方法,結(jié)合實例形式總結(jié)分析了C#創(chuàng)建Access與Excel文件的幾種常用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2016-06-06

