How can I convert string to time in C#?

Hello, I am trying to convert string to time in C#, how can I do that, for example, if I have time as "04:05 pm" in string format, how do I get it as time, timespan, or DateTime format in C#?

Asked by:- bhanu
: 3705 At:- 1/19/2022 3:49:34 PM
C# Datetime

2 Answers
profileImage Answered by:- vikas_jk

You can simply use Convert.ToDateTime or better try to use DateTime.ParseExact by providing format which you will use to pass in the string, to convert string into time, here is the example code, with all possible methods

using System;
public class Program
	public static void Main()
		var time = "04:05 pm";
		DateTime dateTime = DateTime.ParseExact(time, "hh:mm tt",
		// OR
		string Time = "16:23:01";
        DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);

        Console.WriteLine(date.ToString("HH:mm:ss tt"));
		// OR

        DateTime dateNew = Convert.ToDateTime(time);

        Console.WriteLine(dateNew.ToString("HH:mm:ss tt"));


1/19/2022 4:05:00 PM
16:23:01 PM
16:05:00 PM

Here is the fiddle link:


At:- 1/19/2022 4:13:13 PM
Thanks for the reply and fiddle. 0
By : bhanu - at :- 1/20/2022 8:45:10 AM

profileImage Answered by:- pika

you can also try this below simple code to convert string into time in C#

string timeToConvert = "15:23:01";
var result = Convert.ToDateTime(timeToConvert);
string timeOutput= result.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);


At:- 2/21/2022 8:45:53 AM
Thanks 0
By : neena - at :- 2/23/2022 10:19:21 AM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use