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