C# AM/PM 到时间跨度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17553738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:50:13  来源:igfitidea点击:

AM/PM to TimeSpan

c#datetimetimespan

提问by wjm

I want to achieve the converse of this, that is, I want to convert a stringwith format hh:mm ttto a TimeSpanwith zeroed seconds.

我想实现相反的目的,也就是说,我想将 a stringwith 格式转换hh:mm tt为 a TimeSpanwith zeroed seconds。

For example, 09:45 pmis converted to 21:45:00.

例如,09:45 pm转换为21:45:00.

采纳答案by Jon Skeet

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

最简单的方法可能是将其解析为DateTimeusing DateTime.ParseExact,然后使用TimeOfDay来精确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 alsospecifying 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".

但是,当您指定 am/pm 指示符时,在几个小时内看到前导 0 是很奇怪的。您可能需要格式字符串中的“h”而不是“hh”,以允许“9:45 pm”而不是“09:45 pm”。

(I'd also argue that it's a strange use of TimeSpanin 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 :)

(我也认为它首先是一个奇怪的用法TimeSpan,但是在我看来 .NET 日期/时间类型有些混乱。我建议使用Noda Time,但我有偏见:)

回答by ANSHUL VERMA

TimeSpan tspan;

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

回答by Naveed Ahmed

This work for Me.

这为我工作。

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

回答by Rejwanul Reja

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

您可以使用以下代码片段将 meridiem 时间转换为时间跨度,也可以将时间跨度转换为带有日期和时间的 meridiem 时间...

        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

谢谢