簡體   English   中英

json對象包含php DateTime,如何轉換為漂亮的日期字符串

[英]json object contains php DateTime, how to convert to pretty date string

所以我有一個JSON對象,這回我基本上是一個DateTime對象,現在的問題,這是什么格式到一個字符串人類可讀的格式,在用戶(客戶端)本地時區的最有效的方式... 在javascript中

created: {
   timezone: {
      name: "America/New_York",
      location: {
         country_code: "US",
         latitude: 40.71417,
         longitude: -74.00639,
         comments: "Eastern Time"
      }
   },
   offset: -18000,
   timestamp: 1454125056
},

如果時間戳是ECMAScript時間值(即,自1970-01-01T00:00:00Z以來的毫秒數),則可以將該值直接提供給Date對象:

var d = new Date(1454125056); // 1970-01-17T19:55:25.056Z

但是它更可能是秒,因此乘以1,000:

new Date(1454125056*1000).toISOString(); // 2016-01-30T03:37:36.000Z

它將為該時刻創建一個日期。 偏移量可能應該被忽略,除非在時間值的創建中使用了偏移量,在這種情況下,如果它遵循ISO負數表示西方和正數表示東方的規定,則應添加。 如果遵循ECMAScript約定,則相反。

我假設使用ISO,由於它似乎是秒,因此可以將其應用於UTC秒:

var offset = -18000;
d.setUTCSeconds(d.getUTCSeconds() + offset);
console.log(d.toISOString()); // 2016-01-29T22:37:36.000Z

此后使用簡單的Date方法將基於主機系統的時區設置返回值。

 var timeValue = 1454125056; var offset = -18000; var d = new Date(timeValue*1000); document.write(d.toISOString() + '<br>' + d); d.setUTCSeconds(d.getUTCSeconds() + offset); document.write('<br>' + d.toISOString() + '<br>' + d); 

這里有很多關於如何從Date對象格式化日期字符串的問題。

請注意,僅要求javascript考慮當前時間的現行夏令時規則,就好像它們一直存在一樣,因此請注意歷史日期。

假設將此json對象加載到$ created變量中。 我認為你的意思是PHP。

在PHP中:

$obj  = json_decode($created, true);
$timezone_name = $obj['timezone']['name'];
$timezone_location_country_code = $obj['timezone']['location']['country_code'];
$timezone_location_latitude = $obj['timezone']['location']['latitude'];
$timezone_location_longitude = $obj['timezone']['location']['longitude'];
$timezone_location_comments = $obj['timezone']['location']['comments'];
$offset = $obj['offset'];
$timestamp = date('m/d/Y', abs($obj['timestamp']));

在Javascript中:

getDate: function(timestamp){
// Multiply by 1000 because JS works in milliseconds instead of the UNIX seconds
var date = new Date(timestamp * 1000);

var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1; // getMonth() is zero-indexed, so we’ll increment to get the correct month number
var day = date.getUTCDate();
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var seconds = date.getUTCSeconds();

month = (month < 10) ? ‘0’ + month : month;
day = (day < 10) ? ‘0’ + day : day;
hours = (hours < 10) ? ‘0’ + hours : hours;
minutes = (minutes < 10) ? ‘0’ + minutes : minutes;
seconds = (seconds < 10) ? ‘0’ + seconds: seconds;

return year + ‘-‘ + month + ‘-‘ + day + ‘ ‘ + hours + ‘:’ + minutes;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM