C# DateTime.Parse()方法: 将字符串转换为日期时间

  • Post category:C#

DateTime.Parse()是C#中一个将字符串转换为DateTime(日期时间)类型的方法。该方法将输入的字符串按照固定格式解析成DateTime类型的日期时间数据。具体使用方法如下:

DateTime dateTime = DateTime.Parse("2022-09-01");

上述代码将一个字符串“2022-09-01″解析为一个DateTime类型的值,如果想将其他格式的字符串转换为DateTime类型,需要使用ParseExact()方法,并传入一个格式化字符串作为参数,如下所示:

string dateStr = "2022-09-01 08:30";
DateTime dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

上述代码中,第二个参数”yyyy-MM-dd HH:mm”表示日期时间的字符串格式。其中,”yyyy”代表四位数的年份,”MM”代表两位数的月份,”dd”代表两位数的日期,”HH”代表24小时模式下的小时数,”mm”代表分钟数。CultureInfo.InvariantCulture代表使用系统默认的语言环境进行解析。

接下来,我们来看两个实际应用的例子:

  1. 将一个字符串解析为DateTime类型,然后计算时间差值。
string startDateStr = "2022-09-01 08:30";
string endDateStr = "2022-09-01 17:00";

DateTime startDate = DateTime.ParseExact(startDateStr, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact(endDateStr, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

TimeSpan duration = endDate.Subtract(startDate);

Console.WriteLine("工作时长为:" + duration.TotalHours + " 小时");

在上述示例中,我们使用DateTime.ParseExact()方法将字符串解析为DateTime类型的日期时间数据,然后使用DateTime.Subtract方法计算两个时间点的时间差,并输出工作时长。

  1. 将一个字符串解析为DateTime类型,然后将其格式化输出到控制台。
string dateStr = "2022-09-01 08:30";
DateTime dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);

Console.WriteLine(dateTime.ToString("yyyy年M月d日 HH时mm分ss秒"));

在上述示例中,我们使用DateTime.ParseExact()方法将字符串解析为DateTime类型的日期时间数据,然后使用DateTime.ToString()方法将日期时间类型格式化输出,方便用户查看。