2014-10-31 115 views
0

我有一個PHP腳本,它將格式爲2014-10-31T11:28:02+00:00的時間戳字符串傳遞給另一個變量。我怎麼能從這裏減去一小時?更改時間-1小時

例如:

$currDate = $userDate - strtotime('-1 hour');

$userDate包含2014-10-31T11:28:02+00:00

謝謝。

+10

你嘗試之前,在這裏搜索問? – 2014-10-31 11:44:28

+3

http:// php。net/datetime - DateTime類是一件好事。 – 2014-10-31 11:45:43

+0

................. + 1 – 2014-10-31 12:06:54

回答

0

strtotime()是在類似於輸出time()讓你秒的時間戳轉換爲時間。

也就是說,代碼strtotime("-1 hour")將無法​​正常工作。

什麼,但是你可以做的是用戶時間戳轉換爲時間(秒),然後從這一減一小時後,像這樣

$currDate = strtotime($userDate) - 3600; // 1 hour has 3600 seconds 

,然後再轉換$currDate回時間戳,通過做這樣的事情

$finalDate = date("YYYY-mm-dd HH:ss", $currDate); // adjust the format to your needs 

的方式格式化使用date()作品可以發現here

希望有幫助。

+0

只需注意: 'date()'的所有可用格式字符的列表,請參考[官方PHP手冊文檔](http://php.net/date)。 – 2014-10-31 11:52:10

0

你可以使用:

 
$currDate = strtotime($userDate) - 3600; 

如果你想保留$userDate的格式,那麼這樣做:

 
$newUserDate = date("c", strtotime($userDate) - 3600); 
0

使用DateTime類。

  • 從您需要的日期格式
  • 在你想要的格式創建DateTime對象減去小時
  • 回聲的新日期

$date = DateTime::createFromFormat('Y-m-d\TG:i:sP', '2014-10-31T11:28:02+00:00'); 
$date->sub(new DateInterval('PT1H')); 
echo $date->format('Y-m-d\TG:i:sP'); 

https://eval.in/214784

+0

日期採用ISO 8601格式,所以您不需要明確指定格式,因爲PHP的日期解析器已經識別了它。你可以簡單地寫:'$ date = new DateTime($ userDate);'。對於格式化,可以使用['$ date-> format('c');'](http://php.net/date)。 – 2014-10-31 11:50:57

+0

您只能使用'c'格式輸出ISO 8601日期。另外,由於輸入日期是ISO 8601日期,所以不需要格式化輸入,您可以直接輸入新日期時間('2014-10-31T11:28:02 + 00:00')' – AlexL 2014-10-31 11:51:27

1

試試這個:

$str = '2014-10-31T11:28:02+00:00'; 

$dt = DateTime::createFromFormat(DateTime::ISO8601, $str); 
$dt->modify("-1 hours"); 
echo $dt->format(DateTime::ISO8601); 
0

我認爲問題是日期格式。日期和時間戳之間必須有空格。以下作品完美。

$userDate='2014-10-31 T11:28:02+00:00'; 
echo $currDate = $d= date('d-m-Y',strtotime($userDate. " -1 hour")); 
0
$currDate = date('Y-m-d', strtotime($userDate .'-1 hour')); 

試試這個...........在 「年月日」 你把你喜歡的格式爲 「YMD H:我:■」