2014-03-27 19 views
0

我在我的一個項目中使用Kendo UI圖表,今天注意到了在不同瀏覽器中的奇怪行爲,我在x軸上有日期,並且它自動轉換日期不同時區的瀏覽器。Kendo UI圖表根據時區在不同瀏覽器中轉換日期

在UTC + 5中顯示日期範圍從2014年3月1日到2014年3月31日,而在UTC-6中顯示日期範圍從2014年2月28日到2014年3月30日。

回答

0

當試圖解析日期時,如onRequestEnd中此帖所述,收到空響應錯誤。 http://www.telerik.com/support/code-library/using-utc-time-on-both-client-and-server-sides

我通過解析數據源解析方法而不是requestEnd來解決此問題。

parse :function(data) 
      { 
       return ConvertToUTC(data); 
      } 


function ConvertToUTC(data) 
     { 

      // iterate over all the data elements replacing the Date with a version 
      // that Kendo can work with. 
      $.each(data, function(index, item){ 
       if(index == "data") 
       { 

        for(i =0 ;i< item.length; i++) 
        { 
         // Days is my date property in item collection 
         item[i].Days = item[i].Days.replace(/\d+/, 
        function (n) { 
         var time = parseInt(n); 
         return parseInt(time) + new Date(time).getTimezoneOffset() * 60000; 
        } 
       ); 

        } 
       } 
      }); 

      return data; 

     } 
1

基本上,這是由於客戶端和服務器的時區之間的差異而發生的,並且這些日期在兩側傳輸並重新創建爲Date(JS)/ DateTime(.NET)對象。

基本上整個情況詳細解釋here。 Chart使用的dataSource與Grid使用的數據源相同,因此沒有區別。

下面是我可以使用的一個項目的一些示例代碼。檢查requestEnd處理程序

@(Html.Kendo().Grid<KendoMVCWrappers.Models.Person>().Name("persons") 
      .DataSource(dataSource => dataSource 

       .Ajax() 
       .Events(ev => ev.RequestEnd("convert")) 
       .Model(model => model.Id(m => m.PersonID)) 
        .Read(read => read.Action("GetPersons", "Home")) 
        .Update(up => up.Action("UpdatePerson", "Home")) 
      ) 
      .Filterable() 
      .Columns(columns => 
      { 
       columns.Bound(c => c.PersonID); 
       columns.Bound(c => c.Name); 
       columns.Bound(c => c.BirthDate); 
       columns.Command(cmd => cmd.Edit()); 
      }) 
      .Pageable() 
      .Sortable() 
     ) 

<script type="text/javascript"> 
    function convert(e) { 
     if (e.response.Data && e.response.Data.length) { 
      var offsetMiliseconds = new Date().getTimezoneOffset() * 60000; 
      var persons = e.response.Data; 
      for (var i = 0; i < persons.length; i++) { 
       persons[i].BirthDate = persons[i].BirthDate.replace(/\d+/, 
       function (n) { return parseInt(n) + offsetMiliseconds } 
      ); 
      } 
     } 
    } 
</script> 

而ViewModel的setter代碼。使用setter可以簡化整個情況,因爲您必須在多個位置執行此操作(在從數據庫中提取對象並從ModelBinder創建對象時創建對象之前)。

public class Person 
{ 
    public int PersonID { get; set; } 
    public string Name { get; set; } 
    private DateTime birthDate; 
    public DateTime BirthDate 
    { 
     get { return this.birthDate; } 
     set 
     { 
      this.birthDate = new DateTime(value.Ticks, DateTimeKind.Utc); 
     } 

    } 
} 

祝你好運!

+0

感謝您的答覆,是的,我已經嘗試過這種解決方案,但它在返回時返回null。 – saira

相關問題