C# 将 HH.mm 格式的字符串解析为 TimeSpan

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12493381/
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-09 23:26:47  来源:igfitidea点击:

Parse string in HH.mm format to TimeSpan

c#.netstringparsingtime

提问by davioooh

I'm using .NET framework v 3.5and i need to parse a string representing a timespan into TimeSpanobject.

我正在使用.NET 框架 v 3.5,我需要将表示时间跨度的字符串解析为TimeSpan对象。

The problem is that dotseparator is used instead of colon... For example 13.00, or 22.30

问题是使用分隔符而不是冒号...例如13.00,或22.30

So I'm wondering if I have to replace .with :or there is a more clean way to obtain this.

所以我想知道如果我要更换.:或有一个更清洁的方式来获得此。

采纳答案by Ivan G

Parse out the DateTimeand use its TimeOfDayproperty which is a TimeSpanstructure:

解析DateTime并使用其TimeOfDay作为TimeSpan结构的属性:

string s = "17.34";
var ts = DateTime.ParseExact(s, "HH.mm", CultureInfo.InvariantCulture).TimeOfDay;

回答by Darren

string YourString = "01.35";

var hours = Int32.Parse(YourString.Split('.')[0]);
var minutes = Int32.Parse(YourString.Split('.')[1]);

var ts = new TimeSpan(hours, minutes, 0);

回答by Jon

Updated answer:

更新的答案:

Unfortunately .NET 3 does not allow custom TimeSpanformats to be used, so you are left with doing something manually. I 'd just do the replace as you suggest.

不幸的是,.NET 3 不允许使用自定义TimeSpan格式,因此您只能手动执行某些操作。我只是按照你的建议进行更换。

Original answer (applies to .NET 4+ only):

原始答案(仅适用于 .NET 4+):

Use TimeSpan.ParseExact, specifying a custom format string:

使用TimeSpan.ParseExact,指定自定义格式字符串

var timeSpan = TimeSpan.ParseExact("11.35", "mm'.'ss", null);

回答by Habib

For .Net 3.5you may use DateTime.ParseExact and use TimeOfDayproperty

对于.Net 3.5,您可以使用 DateTime.ParseExact 并使用TimeOfDay属性

string timestring = "12.30";
TimeSpan ts = DateTime.ParseExact(
                                  timestring, 
                                  "HH.mm", 
                                  CultureInfo.InvariantCulture
                                  ).TimeOfDay;

回答by Linta Sheelkumar

try This(It worked for me) :

试试这个(它对我有用):

DateTime dt = Convert.ToDateTime(txtStartDate.Text).Add(DateTime.ParseExact(ddlStartTime.SelectedValue, "HH.mm", CultureInfo.InvariantCulture).TimeOfDay);

startdate will be a string like 28/02/2018 and ddlstarttime is in HH format like 13.00

startdate 将是一个像 28/02/2018 这样的字符串,而 ddlstarttime 是像 13.00 这样的 HH 格式

回答by Obaid

If the TimeSpan format is Twelve Hour time format like this "9:00 AM", then use TimeSpan.ParseExact method with format string "h:mm tt", like this

如果 TimeSpan 格式是像这样“9:00 AM”这样的十二小时时间格式,那么使用带有格式字符串“h:mm tt”的 TimeSpan.ParseExact 方法,像这样

TimeSpan ts = DateTime.ParseExact("9:00 AM", "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;

Thanks.

谢谢。