AM/PM to TimeSpan

前端 未结 4 824
忘了有多久
忘了有多久 2020-12-18 18:55

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.

4条回答
  •  既然无缘
    2020-12-18 19:30

    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

提交回复
热议问题