2013-07-16 79 views
1

我需要將其轉換成時間跨度:字符串轉換爲時間跨度

  • 8.3
  • 8.15

當我做它像這樣:

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

它最終會將「10」(上午10點)添加到天而不是它的時間儘管它是一個愚蠢的格式。

+0

單位是時間88小時(上午8時),後點是分鐘 – Smithy

回答

3

你可以做的簡單的方法:

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

我想在有數據類型時 –

+1

@ Rush.2707我列添加15:52:一旦你有一個時間跨度,增加(或減少)的時間段是...簡單:1TimeSpan T1 = getMeSomeTime ();時間跨度T2 = t1.AddHours(15).AddMinutes(52);'如果你有一個'DateTime'值,其'Date'屬性會給你用它的組件'DateTime'值歸零,開始的日,所以'DateTime.Now.Date.AddHours(15).AddMinutes(52)'會給你今天的日期,時間設定爲3:52 pm。 –

10

你可以嘗試以下方法:

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

積分爲在那裏加入了文化信息! – krillgar

+0

這不會爲他的第一個輸入,對不對? – Jonesopolis

+0

@Jonesy正確,它崩潰了我的應用程序 – Smithy

1

頂部的我的腦袋像

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),您可以像我在示例中那樣做。

+0

8.3以8:03進入時應該是8:30? – Smithy

+0

好耶。如果你需要它是30,那麼你需要一些額外的邏輯。我要補充一下 – Jonesopolis

0

這適用於給出的例子:

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

只需提供你所需要的格式。

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