Convert string to TimeSpan

我是研究僧i 提交于 2019-12-11 04:17:10

问题


I need to convert this into a timespan:

  • 8
  • 8.3
  • 8.15

When I do it like so:

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

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.


回答1:


You could do it the straightforward way:

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



回答2:


You could try the following:

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



回答3:


top of my head something like

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

I'm not sure what your goal is with minutes though. If you want 8.3 to be 8:30 then what would 8.7 be? If it's only on 15 minute intervals (15,3,45) you can just do like i did in the example.




回答4:


this works for the examples given:

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:


Just provide the formats that you need.

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

Test to prove it works:

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


来源:https://stackoverflow.com/questions/17682099/convert-string-to-timespan

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!