Datetime parse "2021-04-20T00:09:14.7724640+02:00"

Viewed 121

Best way to parse time = "2021-04-20T00:09:14.7724640+02:00" to valid time. I need seconds as well however once

var h = DateTime.ParseExact(time.Substring(14,5), "hh:mm", CultureInfo.InvariantCulture);

this returns only hour and minute but I need seconds too, however there is 09:14.7724640+02:00 and if I tried hh:mm:ss the "." throws an "Invalid DateTimet "exception

4 Answers
string time = "2021-04-20T00:09:14.7724640+02:00";
DateTime dateTime = DateTime.Parse(time);

With this you have the whole string in the DateTime object and can do whatever you want with it (e.g. cut out hours, minutes and seconds).

You are looking for a timespan, datetime also contains a date part.

If you use the following code you will get a DateTime an a TimeSpan

var timeString = "2021-04-20T00:09:14.7724640+02:00";
var dateTime = DateTime.Parse(timeString);
var time = dateTime.TimeOfDay;
Console.WriteLine(time);

you can use ToString("dd MMMM, yyyy") and give it the format that you want

public static string GetDate(DateTime date)
        {
            return date.ToString("dd MMMM, yyyy");
        }

try this

var time = "2021-04-20T00:09:14.7724640+02:00";
var h = DateTime.Parse(time);
var result = h.ToString("HH:mm:ss");
Related