2014-09-06 159 views
2

我正面臨有關ISO 8601格式日期時間操作的問題。問題是,我有一個日期字符串這樣使用ISO 8601日期格式添加兩秒

string date = "2014-09-05T23:39:57-04:00"; 

我需要額外2秒添加到這個日期。

但是,當我嘗試使用DateTime.Parse方法將此字符串轉換爲添加2秒時,DateTime.Parse方法正在將日期更改爲「9/6/2014 9:09:57 AM」。但我需要這樣的結果

string calculateddate = "2014-09-05T23:39:59-04:00"; 

如何實現這一目標?

感謝 Utpal Maity

回答

1

試試這個:

// you start with this string - it contains a time-zone information 
string date = "2014-09-05T23:39:57-04:00"; 

// this is a DateTimeOffset - and this doesn't have any format - it's a binary blob of 8 bytes 
DateTimeOffset yourDate = DateTimeOffset.Parse(date); 

// add two seconds to it - this is still an 8 byte binary blob .... 
DateTimeOffset twoSecondsAdded = yourDate.AddSeconds(2); 

// display it in the format you want 
string output = twoSecondsAdded.ToString("yyyy-MM-ddTHH:mm:ss K"); 

Console.WriteLine("Date with 2 seconds added: {0}", output); 

,你應該得到的輸出:

Date with 2 seconds added: 2014-09-05T23:39:59 -04:00 

,瞭解這一點很重要

    因爲你
  • 有在你的日期字符串時區符時,必須使用DateTimeOffset
  • 一個DateTimeOffset(或DateTime)在.NET中僅有8個字節的二進制 - 它不具有任何格式
  • 可以顯示DateTimeOffset,無論如何你像 - 只需使用適當的.ToString()覆蓋來指定格式

瞭解更多關於Custom Date and Time Format Strings on MSDN