Asked  7 Months ago    Answers:  5   Viewed   43 times

Code first

    echo time() . '<br/>';
echo date('Y-m-d H:i:s') . '<br/>';
date_default_timezone_set('America/New_York'); 

echo time() . '<br/>';
print_r($timezones[$timezone] . '<br/>');
echo date('Y-m-d H:i:s') . '<br/>';

In the above code the date is printed according to timezone but unix timestamp is same even after setting default timezone

How can we print unix timestamp according to timezone?

 Answers

74

The answer provided by Volkerk (that says timestamps are meant to be always UTC based) is correct, but if you really need a workaround (to make timezone based timestamps) look at my example.

<?php

//default timezone
$date = new DateTime(null);
echo 'Default timezone: '.$date->getTimestamp().'<br />'."rn";

//America/New_York
$date = new DateTime(null, new DateTimeZone('America/New_York'));
echo 'America/New_York: '.$date->getTimestamp().'<br />'."rn";

//Europe/Amsterdam
$date = new DateTime(null, new DateTimeZone('Europe/Amsterdam'));
echo 'Europe/Amsterdam: '.$date->getTimestamp().'<br />'."rn";

echo 'WORK AROUND<br />'."rn";
// WORK AROUND
//default timezone
$date = new DateTime(null);
echo 'Default timezone: '.($date->getTimestamp() + $date->getOffset()).'<br />'."rn";

//America/New_York
$date = new DateTime(null, new DateTimeZone('America/New_York'));
echo 'America/New_York: '.($date->getTimestamp() + $date->getOffset()).'<br />'."rn";

//Europe/Amsterdam
$date = new DateTime(null, new DateTimeZone('Europe/Amsterdam'));
echo 'Europe/Amsterdam: '.($date->getTimestamp() + $date->getOffset()).'<br />'."rn";
?>

Get the regular timestamp and add the UTC offset

Wednesday, March 31, 2021
 
mdevils
answered 7 Months ago
26

Try this:

<?php
echo microtime(true)*1000;
?>
Wednesday, March 31, 2021
 
MDDY
answered 7 Months ago
14

Looking at your question it seems you have the logic the wrong way around. The current time is always bigger then a time in the past. Try the following:

if($time_now>$auction->time_end){
//...
}
Wednesday, March 31, 2021
 
toesslab
answered 7 Months ago
29

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
    system_clock::now().time_since_epoch()
);
Thursday, June 3, 2021
 
Muazam
answered 5 Months ago
79

yep, UNIX timestamp represents how much seconds past from unix-time epoch in GMT+0

Friday, July 16, 2021
 
Kevin_Kinsey
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :