2013-06-12 109 views
0

我有SQL查詢[{date,text,desc},{,,,}]中的JSON,我需要比較日期(date1,date2,...)到多個其他JS日期對象(b1,b2,...)有效。JSON日期與JS日期對象的高效比較

的問題是:目前我有每個JSON日期轉換成JS日期對象之前,我可以對它們進行比較,例如:

(date1->a1) then (a1 to b1) 
else (date2->a2) then (a2 to b1) 
else (daten->an) then (an to b1) 
... then 
(date1->a1) then (a1 to b2) 
else (date2->a2) then (a2 to b2) 
else (daten->an) then (an to b2) 
... and again for each b 

我期待這樣做轉換的一個更有效的方法比較可能有~90'a和30-90'b。

附加信息:

  • JSON日期DESC
  • JS日期是ASC
  • 比較是實現像How do I format a Microsoft JSON date?
  • 當日期符合,則返回該JSON加工對象物
  • 如果沒有日期匹配,返回false
  • 我確實有一個提前退出如果b>一個,但許多早期不會落入這個標準

我在一個JS函數中使用這個插入'文本'字段到谷歌圖表的表。

非常感謝您提前看我的問題!

例JSON:

[ 
    { 
    "id": 797, 
    "title": "test", 
    "description": "test", 
    "annotationDate": { 
     "date": "2013-06-02 00:00:00", 
     "timezone_type": 3, 
     "timezone": "America\/Los_Angeles" 
    }, 
    "discr": "annotation" 
    }, 
    { 
    "id": 806, 
    "title": "recent", 
    "description": null, 
    "annotationDate": { 
     "date": "2013-06-01 00:00:00", 
     "timezone_type": 3, 
     "timezone": "America\/Los_Angeles" 
    }, 
    "discr": "annotation" 
    } 
] 

例JS日期對象:

Date {Sat Jun 01 2013 11:19:35 GMT-0700 (PDT)} 
Date {Sun Jun 02 2013 11:19:35 GMT-0700 (PDT)} 
Date {Mon Jun 03 2013 11:19:35 GMT-0700 (PDT)} 
Date {Tue Jun 04 2013 11:19:35 GMT-0700 (PDT)} 

回答

0

對於每個查詢最新的,它與Number(d)轉換爲數字,並在字典中(JavaScript對象)存儲。循環通過JSON對象,並將每個日期字符串轉換爲Date對象,然後轉換爲數字。檢查這個數字是否存在於字典中。

function filterCharts(json, dates) 
{ 
    var origin = new Date("2000-01-01T00:00:00"); 

    var dateLookup = {}; 
    for (var i = 0; i < dates.length; i++) 
    { 
     var key = dates[i] - origin; // milliseconds 
     key = Math.round(key/86400000); // days 
     dateLookup[key] = true; 
    } 

    var result = []; 
    for (var i = 0; i < json.length; i++) 
    { 
     var jsonDate = new Date(json[i].annotationDate.date.replace(" ", "T")); 
     var key = jsonDate - origin; // milliseconds 
     key = Math.round(key/86400000); // days 
     if (dateLookup[key]) 
     { 
      result.push(json[i]); 
     } 
    } 

    return result; 
} 

我不知道你想如何管理時區,所以我會留給你。

+0

非常感謝你,給了我這個實現變化的開始(把日期本身作爲關鍵字)! 我必須問,var x = {} vs var y = []之間的數據結構/區別是什麼? – Tony

+0

另外,你碰巧知道爲什麼我得到'var jsonDate = new Date(json [i] .annotationDate.date);'作爲無效日期? 我必須將它轉換爲String並使用setFullyear,setMonth,setDate! – Tony

+0

Ecma腳本標準定義的有效日期字符串爲''或' T