2

I wonder if it's possible to get the global UTC time without relying on the server time (or in my case on my PC time).

As for now, if I do

date('H:i:s')

I get my PC time (the only change is the GMT+3 or GMT+2 that I set in the app itself) so if I change my PC time to 2 hours and 23 minutes back, then the date() function result will also be 2 hours and 23 minutes back.

Is it possible to always pull the global UTC time regardless of my own PC watch?

kfirba
  • 5,231
  • 14
  • 41
  • 70
  • http://stackoverflow.com/questions/8655515/get-utc-time-in-php – Cheery Oct 12 '14 at 21:56
  • Check this link which gets time from [Google][1] [1]: http://stackoverflow.com/questions/12674411/php-get-time-from-a-specific-server – Turay Melo Oct 12 '14 at 22:02
  • 1
    @Cheery It doesn't work. If I change my PC clock, the function returns the time according to my PC clock still. – kfirba Oct 12 '14 at 22:02
  • @kfirba do you mean `your server` = `your pc`? than there is no way to do it. you can make request to the time server, but you have to keep and to update this value correspondingly between http requests to your server as you can not do this time request with each http request. – Cheery Oct 12 '14 at 22:04

2 Answers2

3

@Cheery provided a nice link in the question comments, but as of it's 2014 outside - it makes sense to use modern tools for that:

$dt = new DateTime('now', new DateTimeZone('UTC'));
echo $dt->format('d-m-Y H:i:s');

And answering your the only question:

Is it possible to always pull the global UTC time regardless of my own PC watch?

No, php expects your local clock + OS/php timezone settings are correct.

References:

zerkms
  • 249,484
  • 69
  • 436
  • 539
0

You can solve your problem with a web service, but you'd have to pass the Unix time as an argument.

For instance, using the World Weather Online API (without any validation; you'd need to register and use your API Key):

<?php
$loc = 'utc'; 
$key = 'xkq544hkar4m69qujdgujn7w';

$url = 'http://api.worldweatheronline.com/free/v1/tz.ashx?format=json&'
       . http_build_query(array('key' => $key, 'q' => $loc,));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1); 
$json_response = curl_exec($ch);
curl_close($ch);

$response = json_decode($json_response);
$tz = $response->data->time_zone[0]->localtime;

$timestamp = strtotime($tz);

var_dump($tz);
var_dump( date('H:i', $timestamp) );

This service does not retrieve the seconds (it's just an example; you can choose other services), but you can make your own service:

<?php
date_default_timezone_set('UTC');
header('Content-Type: application/json');
echo json_encode(array('timestamp' => time()));

On the other hand, you could use a Network Time Protocol:

Pedro Amaral Couto
  • 2,056
  • 1
  • 13
  • 15