一、C#字元串轉換為DateTime類型
在C#中,將字元串轉換為時間類型可以使用DateTime類的靜態Parse()方法。需要注意的是,輸入的字元串必須符合DateTime類的ToString()方法返回的字元串格式,否則會拋出FormatException異常。
using System;
class Program {
static void Main(string[] args) {
string str = "2022-03-01 18:30:00";
DateTime time = DateTime.Parse(str);
Console.WriteLine("轉換後的時間為:" + time);
}
}
二、指定字元串格式轉換為DateTime類型
如果輸入的字元串不符合標準的時間格式,就需要指定格式進行轉換。可以使用DateTime類的靜態ParseExact()或TryParseExact()方法,兩者區別在於ParseExact()方法在轉換失敗時會拋出異常,而TryParseExact()方法返回是否轉換成功。
using System;
class Program {
static void Main(string[] args) {
string str = "2022-03-01T18:30:00Z";
string format = "yyyy-MM-ddTHH:mm:ssZ";
DateTime time;
if (DateTime.TryParseExact(str, format, null, System.Globalization.DateTimeStyles.None, out time)) {
Console.WriteLine("轉換後的時間為:" + time);
} else {
Console.WriteLine("轉換失敗");
}
}
}
三、處理日期格式不一致的情況
在實際開發中,經常遇到不同格式的日期字元串,需要進行統一處理。可以使用DateTime類的ToString()方法和ParseExact()方法配合使用,將日期字元串先轉換為標準格式,再進行轉換。
using System;
class Program {
static void Main(string[] args) {
string str1 = "2022/3/1";
string str2 = "2022-03-01 18:30:00";
string format1 = "yyyy/M/d";
string format2 = "yyyy-MM-dd HH:mm:ss";
string standardStr1, standardStr2;
DateTime time;
// 轉換str1
if (DateTime.TryParseExact(str1, format1, null, System.Globalization.DateTimeStyles.None, out time)) {
standardStr1 = time.ToString(format2);
} else {
Console.WriteLine("轉換失敗");
return;
}
// 轉換str2
if (DateTime.TryParseExact(str2, format2, null, System.Globalization.DateTimeStyles.None, out time)) {
standardStr2 = time.ToString(format2);
} else {
Console.WriteLine("轉換失敗");
return;
}
Console.WriteLine("轉換後的時間1為:" + DateTime.Parse(standardStr1));
Console.WriteLine("轉換後的時間2為:" + DateTime.Parse(standardStr2));
}
}
四、其他相關問題
如何將C# DateTime類型轉換為字元串?
可以使用DateTime類的ToString()方法,傳入指定的格式即可。
DateTime time = DateTime.Now;
string str = time.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine("轉換後的字元串為:" + str);
如何獲取當前時間?
可以使用DateTime類的靜態Now屬性。
DateTime now = DateTime.Now;
Console.WriteLine("當前時間為:" + now);
如何將時間戳轉換為DateTime類型?
可以使用Unix時間戳轉換為DateTime類型的方法,即將Unix時間戳轉換為DateTime對象。
string timeStamp = "1646131800"; // 時間戳的字元串形式
DateTime time = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
.AddSeconds(Convert.ToDouble(timeStamp))
.ToLocalTime();
Console.WriteLine("轉換後的時間為:" + time);
原創文章,作者:YIDX,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/135191.html
微信掃一掃
支付寶掃一掃