2013-07-31 38 views
6

我有三個項目的解決方案:UTC轉換爲本地時間返回奇怪的結果

  1. 核心
  2. Outlook加載
  3. ASP.NET網站

兩個,觀加載項和網站使用Core項目中的相同方法從SQL Server獲取數據。當我寫我的數據到數據庫中,我轉換兩個表的所有DateTime值轉換成UTC時間:

POLL_START    POLL_END 
2013-07-31 12:00:00.000 2013-08-01 12:00:00.000 

PICK_DATE 
2013-07-31 12:00:48.000 
2013-07-31 13:00:12.000 

當我在我的Outlook加載數據,這是正確的結果

enter image description here enter image description here

當在我的網站打開一樣,首選是罰款:

enter image description here

但我的開始和結束時間是「破」 - 偏移量增加,弼錯誤的時間使用:

enter image description here

下面是我的轉換代碼,這兩個,Outlook和網站,使用:

private static void ConvertToLocalTime(POLL item) 
{ 
    item.POLL_START = item.POLL_START.FromUTC(); 
    item.POLL_END = item.POLL_END.FromUTC(); 
} 

private static void ConvertToLocalTime(PICK pick) 
{ 
    if (pick.PICK_DATE != null) pick.PICK_DATE = ((DateTime)pick.PICK_DATE).FromUTC(); 
} 

DateTime.FromUtc()實現:

public static DateTime FromUTC(this DateTime value) 
{ 
    var local = TimeZoneInfo.Local; 
    return TimeZoneInfo.ConvertTime(value, TimeZoneInfo.Utc, local); 
} 

我有同樣的結果與DateTime.ToLocalTime()。 任何想法?

編輯1:

這是起點和終點如何被顯示在網站上(最終與End代替Start):

var startCell = new TableCell 
     { 
      Text = String.Format(
       @"<a href='{0}' title='{2}' target='_blank'>{1:dd.MM.yyyy HH:mm \U\T\Czzz}</a>", 
        Common.GetTimeAndDateHyperlink(_poll.Start, "Vote Start"), 
        _poll.Start, 
        ConvertToLocalTimeZone), 
      CssClass = "InfoContent" 
     }; 

而且選秀:

answerCell = new TableCell 
      { 
       Text = String.Format(
        @"<a href='{0}' title='{2}' target='_blank'>{1}</a>", 
         Common.GetTimeAndDateHyperlink(ao.Time, ao.RealAnswer), 
         ao.RealAnswer, 
         ConvertToLocalTimeZone) 
      }; 

ao.RealAnswer返回格式化的DateTime字符串:

return String.Format(WholeTime == true ? "{0:d}" : @"{0:dd.MM.yyyy HH:mm \U\T\Czzz}", Time); 
+0

你正在使用什麼代碼來顯示你的網頁上的時間? – Romoku

+0

@Romoku添加了代碼 – Herdo

+0

我要猜測兩者之間的[Kind](http://msdn.microsoft.com/en-us/library/system.datetime.kind.aspx)屬性是不同的。 – Greg

回答

1

我現在解決了這個問題。開始和結束的DateTime值未正確轉換:值未輸出到當地時間。

原因,爲什麼網站上顯示的時間爲當地時間,即SQL服務器存儲每DateTime值作爲DateTimeKind.Unspecified而不是保持插入過程中指定數據(例如DateTimeKind.Utc)。當從服務器讀取數據時,所有種類都是DateTimeKind.Unspecified,因此.ToString()DateTime使用本地種類。這導致UTC時間爲+本地UTC時間偏移