Parse string in HH.mm format to TimeSpan

35,969

Solution 1

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;

Solution 2

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);

Solution 3

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);

Solution 4

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;

Solution 5

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.

Share:
35,969
davioooh
Author by

davioooh

Hi, I'm David Castelletti. I like to create things with Java & Kotlin (❤). LinkedIn profile Personal Page + Blog (italian)

Updated on May 08, 2020

Comments

  • davioooh
    davioooh about 4 years

    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.