2017-08-23 34 views
0

我有一個JSON輸入。我想將所有時間戳(createdDate,modifiedDate)轉換爲ruby中的時間。我怎麼做?我嘗試下面的方法,但憑着工作Ruby:在給定的json輸入中將時間戳轉換爲日期時間

characterList.each { |char| DateTime.strptime(char.try(:getEditInfo).try(:getCreatedDate),%s) } 


{"characterList": 
    [ 
    {"editInfo": 
     {"createdBy": "testname", 
     "createdDate": 1503137795000, 
     "modifiedBy": "testname", 
     "modifiedDate": 1503137795000}, 
    "charInfo": 
     {"charid": "3434", 
     "charDesc": "3434", 
     "status": "ON"} 
    }, 
    {"editInfo": 
     {"createdBy": "testname", 
     "createdDate": 1503137795000, 
     "modifiedBy": "testname", 
     "modifiedDate": 1503137795000}, 
    "charInfo": 
     {"charid": "3434 6", 
     "charDesc": "43dfdf", 
     "status": "ON"} 
    }, 
    {"editInfo": 
     {"createdBy": "testname", 
     "createdDate": 1503137795000, 
     "modifiedBy": "testname", 
     "modifiedDate": 1503137795000}, 
    "charInfo": 
     {"charid": "4hr_SLA", 
     "charDesc": "sd", 
     "status": "ON"} 
    }, 
    {"editInfo": 
     {"createdBy": "testname", 
     "createdDate": 1503137795000, 
     "modifiedBy": "testname", 
     "modifiedDate": 1503137795000}, 
    "charInfo": 
     {"charid": "aaaaaaaaaa", 
     "charDesc": "asdfaadsf asdfasdf asdf", 
     "status": "ON"} 
    }, 
    {"editInfo": 
     {"createdBy": "testname", 
     "createdDate": 1503137795000, 
     "modifiedBy": "testname", 
     "modifiedDate": 1503137795000}, 
    "charInfo": 
     {"charid": "abababab", 
     "charDesc": "abababababab", 
     "status": "ON"} 
    } 
    ]} 

我行分別爲createdDate和modifiedDate 2轉換等。但是我在尋找一個在線解決方案

回答

1

你可以這樣做:

json[:characterList].map! do |character| 
    character.tap do |char| 
    if editInfo = char[:editInfo] 
     if editInfo[:createdDate] 
     editInfo[:createdDate] = 
      DateTime.strptime(editInfo[:createdDate].to_s, '%Q') 
     end 

     if editInfo[:modifiedDate] 
     editInfo[:modifiedDate] =_ 
      DateTime.strptime(editInfo[:modifiedDate].to_s, '%Q') 
     end 
    end 
    end 
end 

與您的代碼的主要問題是

  1. 沒有:getEditInfo:getCreatedDate,不過,這些可能只是方法你但沒有包括在這裏。
  2. strptime需要一個字符串,該*Date領域是整數
  3. %s參數strptime秒數量因爲1970-01-01 00:00:00 UTC,我會假設你是不是在今年49602處理日期,所以將其更改爲%Q,這是毫秒的數量1970-01-01 00:00:00 UTC

這只是一個樣本,修改JSON哈希本身DateTime對象,你可能需要做一些與它不同,這裏的一件大事是在%Qto_sstrptime小號

DateTime.strptime(1503137795000.to_s, '%Q') # => 2017-08-19T10:16:35+00:00 

不知道什麼是真正你的代碼錯誤(「不工作」是不是很描述),如果一切都在該行你嘗試過其他的工作你可以只改變爲:

characterList.each { |char| DateTime.strptime(char.try(:getEditInfo).try(:getCreatedDate).to_s,'%Q') } 

單線程

相關問題