将字符串转换为TimeSpan [英] Convert string to TimeSpan

查看:177
本文介绍了将字符串转换为TimeSpan的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to convert this into a timespan:

  • 8
  • 8.3
  • 8.15

当我这样做时:

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

它最终会在几天内而不是在时间上加上"10"(上午10点),尽管这是一种愚蠢的格式.

It will end up adding say '10' (10am) into days rather than the time that it is, albeit in a stupid format that it is.

推荐答案

您可以直接这样做:

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

这篇关于将字符串转换为TimeSpan的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆