[英]Get Time from timestamp in php
I am using Forecast.io
weather api to get weather data. 我正在使用
Forecast.io
天气API来获取天气数据。 I have a little problem while i display sunrise and sun set time of that location. 在显示该位置的日出和日落时间时,我遇到了一个小问题。
it give time in time-stamp format also provide offset hour difference so i did following code to get time 它以时间戳格式给出时间,还提供了偏移时差,所以我按照以下代码来获取时间
//following GMT value or offset get from api
$offsetHours = '-5 hours';
// This time i get from api
$currentValue = '1401705628';
$actualTimeStamp = strtotime($offsetHours,$currentValue);
echo $actualTimeStamp;
echo date('h:i A',$actualTimeStamp);
Last echo time is actual time that is '5:40 AM' i got but in some php version it gives wrong result. 最后的回显时间是我得到的“ 5:40 AM”的实际时间,但是在某些php版本中,它给出了错误的结果。
so is there any other way to doing this i cannot update my php version 所以有没有其他办法做到这一点,我不能更新我的PHP版本
date('h:i A', (time()-(60*60*5)));
gmdate('Ymd H:i:s', strtotime ('+1 hour'))
you can be as flexible as you like with how many hours you want to go forward or back ie(- 1 hour). gmdate('Ymd H:i:s', strtotime ('+1 hour'))
您可以根据自己的喜好灵活选择前进或后退几个小时,即(-1小时)。 But have to use strtotime PHP function :) 但是必须使用strtotime PHP函数:)
Have you tried using the \\DateTime Object of php? 您是否尝试过使用php的\\ DateTime对象? Try something like this:
尝试这样的事情:
$currentValue = '1401705628';
$offsetHours = '-5 hours';
//Create DateTime Object With Date = NOW()
$date = new \DateTime();
//set Timestamp to DateTime Object
$date->setTimestamp($currentValue);
//Its the date from the timestamp
echo $date->format('h:i A') . '<br><br>';
$pattern = '/^([\+|\-]?)(\d+)\s(hours|hour|minutes|minute)$/iU';
$match = array();
if (preg_match($pattern, $offsetHours, $match)){
//$match contains an array of matching elements of the pattern
// $match[0] = '-5 hours'
// $match[1] = '-'
// $match[2] = '5'
// $match[3] = 'hours'
//Creating the DateInterval String
$intervalStr = 'PT' . $match[2] . strtoupper(substr($match[3], 0, 1));
// Create an object of the DateInterval
$dateInterval = new \DateInterval($intervalStr);
if ($match[1] === '-'){
//Substract the DateInterval from Date
$date->sub($dateInterval);
}
else {
//Add the Dateinterval to date
$date->add($dateInterval);
}
} //if preg_match
//Its the date with the offset
echo $date->format('h:i A');
EDIT:: I've updated my example to resolve the time offset dynamically 编辑::我更新了示例以动态解决时间偏移
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.