Parse string in HH.mm format to TimeSpan

后端 未结 6 1579
栀梦
栀梦 2020-12-06 03:57

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

相关标签:
6条回答
  • 2020-12-06 04:35

    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;
    
    0 讨论(0)
  • 2020-12-06 04:35

    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

    0 讨论(0)
  • 2020-12-06 04:37

    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;
    
    0 讨论(0)
  • 2020-12-06 04:56

    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);
    
    0 讨论(0)
  • 2020-12-06 04:56

    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.

    0 讨论(0)
  • 2020-12-06 05:00
    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);
    
    0 讨论(0)
提交回复
热议问题