Parse string in HH.mm format to TimeSpan

2019-01-14 20:32发布

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

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

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

6条回答
倾城 Initia
2楼-- · 2019-01-14 21:09
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);
查看更多
forever°为你锁心
3楼-- · 2019-01-14 21:10

Updated answer:

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

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

Use TimeSpan.ParseExact, specifying a custom format string:

var timeSpan = TimeSpan.ParseExact("11.35", "mm'.'ss", null);
查看更多
▲ chillily
4楼-- · 2019-01-14 21:10

For .Net 3.5 you may use DateTime.ParseExact and use TimeOfDay property

string timestring = "12.30";
TimeSpan ts = DateTime.ParseExact(
                                  timestring, 
                                  "HH.mm", 
                                  CultureInfo.InvariantCulture
                                  ).TimeOfDay;
查看更多
Melony?
5楼-- · 2019-01-14 21:14

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 ts = DateTime.ParseExact("9:00 AM", "h:mm tt", CultureInfo.InvariantCulture).TimeOfDay;

Thanks.

查看更多
趁早两清
6楼-- · 2019-01-14 21:16

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

查看更多
劫难
7楼-- · 2019-01-14 21:27

Parse out the DateTime and use its TimeOfDay property which is a TimeSpan structure:

string s = "17.34";
var ts = DateTime.ParseExact(s, "HH.mm", CultureInfo.InvariantCulture).TimeOfDay;
查看更多
登录 后发表回答