[C #] Convert date and time character string to DateTime type

1 minute read

Overview

You can use the “Parse” or “TryParth” methods to convert a string to a DateTime type in C #.

Parse method

python


//There is a date and time
string strDateTime = "2020/10/22 15:01:11";
DateTime dateTime = DateTime.Parse(strDateTime);
Console.WriteLine(dateTime.ToString("yyyy/MM/dd HH:mm:ss"));

//Time omitted
string strDate = "2020/10/22";
DateTime dateTimeFromDate = DateTime.Parse(strDate);
Console.WriteLine(dateTimeFromDate.ToString("yyyy/MM/dd HH:mm:ss"));

//Date omitted
string strTime = "15:01:11";
DateTime dateTimeFromTime = DateTime.Parse(strTime);
Console.WriteLine(dateTimeFromTime.ToString("yyyy/MM/dd HH:mm:ss"));

Execution result


2020/10/22 15:01:11
2020/10/22 00:00:00
2020/08/22 15:01:11

The date and time can be omitted.
If the time is not entered, 00:00:00 will be entered.
If no date is entered, the current date will be entered.

exception

If the string to be passed is null, “ArgumentNullException” will be issued.
If the character string to be passed cannot be determined as the date and time, “FormatException” will be issued.

TryParse method

Specify the character string to be converted in the first argument, and the date and time after conversion is stored in the DateTime type specified in the second argument. It also returns a value that indicates whether the conversion was successful.

python


string strDateTime = "2020/10/22 15:01:11";
DateTime dateTime;

if (DateTime.TryParse(strDateTime, out dateTime))
{
Console.WriteLine("success!");
Console.WriteLine(dateTime.ToString("yyyy/MM/dd HH:mm:ss"));
} else {
Console.WriteLine("Failure!");
Console.WriteLine(dateTime);
}

Execution result


success!
2020/10/22 15:01:11

reference

https://docs.microsoft.com/ja-jp/dotnet/api/system.datetime.parse?view=netcore-3.1
https://docs.microsoft.com/ja-jp/dotnet/api/system.datetime.tryparse?view=netcore-3.1