C# 将字符串转换为时间跨度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17682099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert string to TimeSpan
提问by Smithy
I need to convert this into a timespan:
我需要将其转换为时间跨度:
- 8
- 8.3
- 8.15
- 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.
它最终会将“10”(上午 10 点)添加到天而不是现在的时间,尽管它是一种愚蠢的格式。
采纳答案by Nicholas Carey
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 ;
}
回答by Leigh
You could try the following:
您可以尝试以下操作:
var ts = TimeSpan.ParseExact("0:0", @"h\:m",
CultureInfo.InvariantCulture);
回答by Jonesopolis
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.
不过我不确定你的目标是什么。如果您希望 8.3 是 8:30,那么 8.7 会是什么?如果它只是 15 分钟的时间间隔(15,3,45),您可以像我在示例中那样做。
回答by 1c1cle
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);
回答by Matt Johnson-Pint
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);
}