2013-10-01 115 views
0

我們的數據庫服務器是在國外的..所以我存儲在使用的TimeZoneInfo像下面的創建日期,顯示時間跨度值後改爲當地時間

DateTime dateTime = DateTime.Now; 
     var timeZone = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTime, TimeZoneInfo.Local.Id, "India Standard Time"); 

在頁面上,我顯示使用Timespan。我創建單獨的類的..

我的代碼

public static string GetFriendlyDate(DateTime dateTime) 
    { 
     TimeSpan ts = DateTime.Now.Subtract(dateTime); 

     string friendlyDate = dateTime.ToShortDateString(); 
     int totalDays = (int)System.Math.Round(ts.TotalDays); 
     int totalHours = (int)System.Math.Round(ts.TotalHours); 
     int totalMinutes = (int)System.Math.Round(ts.TotalMinutes); 
     int totalSeconds = (int)System.Math.Round(ts.TotalSeconds); 
     int totalMilliSeconds = (int)System.Math.Round(ts.TotalMilliseconds); 

     int totalMonths = totalDays/31; //approx.. change this 
     int totalYears = totalDays/365; //approx.. change this 

     if (totalYears > 0) //give in terms of years 
     { 
      if (totalYears == 1) 
       friendlyDate = "last year"; 
      else 
       friendlyDate = totalYears + " years ago"; 
     } 
     else if (totalMonths > 1) //give in terms of months 
     { 
      if (totalMonths == 1) 
       friendlyDate = "last month"; 
      else 
       friendlyDate = totalMonths + " months ago"; 
     } 
     else if (totalDays > 1) //give in terms of days (at least 2 days) 
     { 
      friendlyDate = totalDays + " days ago"; 
     } 
     else if (totalHours > 0) //give in terms of hours 
     { 
      if (totalHours == 1) 
       friendlyDate = "1 hour ago"; 
      else 
       friendlyDate = totalHours + " hours ago"; 
     } 
     else if (totalMinutes > 0) // give in terms of minutes 
     { 
      if (totalMinutes == 1) 
       friendlyDate = "1 minute ago"; 
      else 
       friendlyDate = totalMinutes + " minutes ago"; 
     } 
     else if (totalSeconds > 0) //give in terms of seconds 
     { 
      if (totalSeconds == 1) 
       friendlyDate = "1 second ago"; 
      else 
       friendlyDate = totalSeconds + " seconds ago"; 
     } 
     else //just now 
     { 
      friendlyDate = "a moment ago"; 
     } 

     return friendlyDate; 
    } 

當我運行本地它顯示了正確的「前--seconds」 ......這樣的。但在服務器它總是顯示剛纔,幾個小時後,它正在採取「---小時前」那樣..

任何人都可以請幫我解決這個問題嗎?

回答

0

如果我想得到一個正確的方式我問我的問題,我必須將時間轉換爲UTC。

,所以我改變了..

var utcTime = DateTime.UtcNow.AddHours(5).AddMinutes(30); 
     TimeSpan ts = utcTime.Subtract(dateTime); 

現在的問題就解決了......

0

你被存儲的項目,如印度標準時間,然後比較它們對本地時間。

您在答案中給出的解決方案是將時間調整回到印度標準時間,該時間固定爲UTC的+5:30偏移量。這僅適用於IST沒有任何夏時制規則。如果您使用不同的時區(如美國東部時間),則無法可靠運行。

正確的解決方案是將原始值存儲爲UTC。而不是使用DateTime.Now並轉換爲IST,只需使用DateTime.UtcNow並直接存儲值。當您在​​3210方法中比較時,還應該使用DateTime.UtcNow作爲比較的基礎。

如果您已將數據保存在印度標準時間的數據庫中,則在進行此更改時需要更新這些值。例如,如果這是SQL Server,您可以運行下面的腳本來更新你的價值從IST到UTC:

UPDATE mytable SET thedatetime = DATEADD(minute, -330, thedatetime) 

在一般情況下,本地的日期/時間值,如那些來自DateTime.Now檢索有沒有業務一個Web應用程序。閱讀The Case Against DateTime.Now