28

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.

Darren
  • 68,902
  • 24
  • 138
  • 144
davioooh
  • 23,742
  • 39
  • 159
  • 250

6 Answers6

50

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;
Appulus
  • 18,630
  • 11
  • 38
  • 46
Ivan Golović
  • 8,732
  • 3
  • 25
  • 31
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);
Jon
  • 428,835
  • 81
  • 738
  • 806
4
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);
Darren
  • 68,902
  • 24
  • 138
  • 144
2

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;
Habib
  • 219,104
  • 29
  • 407
  • 436
  • This solution rocks! I found it on my own but it's so simple, now you get all the usual DateTime formatting options that we know and love and can use them for TimeSpan the way we expected the first time. - Note this obviously wont work for Timespans greater than 24 hours... but most of the time I have been using TimeSpan when integrating with external systems that track dates and times separately, so we never go past 23:59:59 :) – Chris Schaller Aug 17 '16 at 00:48
2

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.

Obaid
  • 2,563
  • 17
  • 15
0

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

Linta Sheelkumar
  • 195
  • 1
  • 5
  • 21