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#?
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",
System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(dateTime);
// 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"));
}
}
Output:
1/19/2022 4:05:00 PM
16:23:01 PM
16:05:00 PM
Here is the fiddle link: https://dotnetfiddle.net/LgGg2g
Thanks
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);
Thanks
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly