wjmolina
wjmolina

Reputation: 2675

AM/PM to TimeSpan

I want to achieve the converse of this, that is, I want to convert a string with format hh:mm tt to a TimeSpan with zeroed seconds.

For example, 09:45 pm is converted to 21:45:00.

Upvotes: 27

Views: 36253

Answers (5)

zvi shmuel naiman
zvi shmuel naiman

Reputation: 1

The only way that worked for me is Convert.ToDateTime(str).TimeOfDay. ParseExact resulted with an error!

string str = "12:01 AM";
TimeSpan ts = Convert.ToDateTime(str).TimeOfDay;

taken from: https://social.msdn.microsoft.com/Forums/vstudio/en-US/200b35bf-9d35-4348-80a7-9f31ee91c64c/convert-short-time-string-to-time-span?forum=csharpgeneral

Upvotes: 0

Rejwanul Reja
Rejwanul Reja

Reputation: 1491

You can convert meridiem time to timespan and also timespan to meridiem time with date and only time using below code snipet...

        TimeSpan ts = DateTime.Parse("8:00 PM").TimeOfDay;                        
        DateTime dateWithTimeSlot = DateTime.Today+ ts;              

        //for getting MM/dd/yyyy hh:mm tt format
        string dateWithMeridiemTimeSlot =  
            dateWithTimeSlot.ToString("MM/dd/yyyy hh:mm tt: ", CultureInfo.InvariantCulture);

        Console.WriteLine("For getting MM/dd/yyyy hh:mm tt format: "+dateWithMeridiemTimeSlot);

        //for getting only hh:mm tt format
        string meridiemTimeSlot =
            dateWithTimeSlot.ToString("hh:mm tt", CultureInfo.InvariantCulture);

        Console.WriteLine("For getting only hh:mm tt format: " + meridiemTimeSlot);

        Console.ReadLine();

Let's enjoy!

Thanks

Upvotes: 0

Naveed Ahmed
Naveed Ahmed

Reputation: 493

This work for Me.

TimeSpan ts= DateTime.Parse("8:00 PM").TimeOfDay; 

Upvotes: 26

ANSHUL VERMA
ANSHUL VERMA

Reputation: 1

TimeSpan tspan;

tspan = DateTime.ParseExact("01:45 PM", "hh:mm tt", CultureInfo.InvariantCulture).TimeOfDay;

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500595

The simplest approach would probably be to parse it as a DateTime using DateTime.ParseExact, and then use the TimeOfDay to exact the TimeSpan.

DateTime dateTime = DateTime.ParseExact(text,
                                    "hh:mm tt", CultureInfo.InvariantCulture);
TimeSpan span = dateTime.TimeOfDay;

It's odd to see a leading 0 on a number of hours when you're also specifying an am/pm designator though. You might want "h" instead of "hh" in the format string, to allow "9:45 pm" instead of "09:45 pm".

(I'd also argue that it's a strange use of TimeSpan in the first place, but then the .NET date/time types are somewhat messed up in my view. I'd recommend using Noda Time, but I'm biased :)

Upvotes: 76

Related Questions