【问题标题】:Convert string to TimeSpan将字符串转换为时间跨度
【发布时间】:2013-07-16 16:30:18
【问题描述】:

我需要将其转换为时间跨度:

  • 8
  • 8.3
  • 8.15

当我这样做时:

DateTime s = booking.TourStartDate.Add(TimeSpan.Parse(booking.TourStartTime.Replace(".", ":")));

它最终会将“10”(上午 10 点)添加到几天而不是现在的时间,尽管它的格式很愚蠢。

【问题讨论】:

  • 单位是时间 8 是 8 小时(上午 8 点),点之后是分钟

标签: c# parsing timespan


【解决方案1】:

您可以尝试以下方法:

var ts = TimeSpan.ParseExact("0:0", @"h\:m",
                             CultureInfo.InvariantCulture);

【讨论】:

    【解决方案2】:

    你可以直接做:

    static Regex myTimePattern = new Regex( @"^(\d+)(\.(\d+))?$") ;
    static TimeSpan MyString2Timespan( string s )
    {
      if ( s == null ) throw new ArgumentNullException("s") ;
      Match m = myTimePattern.Match(s) ;
      if ( ! m.Success ) throw new ArgumentOutOfRangeException("s") ;
      string hh = m.Groups[1].Value ;
      string mm = m.Groups[3].Value.PadRight(2,'0') ;
      int hours   = int.Parse( hh ) ;
      int minutes = int.Parse( mm ) ;
      if ( minutes < 0 || minutes > 59 ) throw new ArgumentOutOfRangeException("s") ;
      TimeSpan value = new TimeSpan(hours , minutes , 0 ) ;
      return value ;
    }
    

    【讨论】:

    • 我想在数据类型为 time 的列中添加下午 3:52
    • @Rush.2707:一旦你有了 TimeSpan,添加(或减去)时间段很容易:1TimeSpan t1 = getMeSomeTime(); TimeSpan t2 = t1.AddHours(15).AddMinutes(52);` 如果你有一个DateTime 值,它的Date 属性会给你一个DateTime 值,它的时间分量归零到一天的开始,所以DateTime.Now.Date.AddHours(15).AddMinutes(52) 会给你今天的日期,时间设置为下午 3:52。
    【解决方案3】:

    我的头顶像

    string[] time = booking.TourStartTime.Split('.');
    
    int hours = Convert.ToInt32(time[0]);
    int minutes = (time.Length == 2) ? Convert.ToInt32(time[1]) : 0;
    
    if(minutes == 3) minutes = 30;
    
    TimeSpan ts = new TimeSpan(0,hours,minutes,0);
    

    不过,我不确定您的分钟目标是什么。如果您希望 8.3 是 8:30,那么 8.7 会是什么?如果仅间隔 15 分钟 (15,3,45),您可以像我在示例中那样做。

    【讨论】:

    • 8.3 在应该是 8:30 时以 8:03 出现?
    • 好吧。如果你需要它是 30,那么你需要一些额外的逻辑。我来补充一下
    【解决方案4】:

    这适用于给出的示例:

    double d2 = Convert.ToDouble("8"); //convert to double
    string s1 = String.Format("{0:F2}", d2); //convert to a formatted string
    int _d = s1.IndexOf('.'); //find index of .
    TimeSpan tis = new TimeSpan(0, Convert.ToInt16(s1.Substring(0, _d)), Convert.ToInt16(s1.Substring(_d + 1)), 0); 
    

    【讨论】:

      【解决方案5】:

      只需提供您需要的格式即可。

      var formats = new[] { "%h","h\\.m" };
      var ts = TimeSpan.ParseExact(value, formats, CultureInfo.InvariantCulture);
      

      测试以证明它有效:

      var values = new[] { "8", "8.3", "8.15" };
      var formats = new[] { "%h","h\\.m" };
      
      foreach (var value in values)
      {
          var ts = TimeSpan.ParseExact(value, formats, CultureInfo.InvariantCulture);
          Debug.WriteLine(ts);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多