Timezone and datetime php - php

I don't really understand how the datetime works.
for example if I create a dateTime
$date = new DateTime();
echo $date->('H');
Did the hour will be generated in function to the server time or the user time ?
If this is the server timezone, is there a way to convert it to the user timezone
Thanks for your help

PHP is server side. The hour is generated is server time.
If you want client's(user) time you must use JavaScript.
You maybe want to use JavaScript.
example
echo "<script type=\"text/javascript\">";
echo "localtime = new Date();";
echo "alert(localtime.getHours());";
echo "</script>";

knowing the current server date such
$current = strtotime(date("Y-m-d H:m:s")) //return timestamp
can add or subtract hours to result your time to set the current date variable at the user level:
$new_time = date($current, strtotime('+5 hours')

Related

Show text after a date has passed

I am trying to get a simple line of text to appear if todays date is after another date.
I can either get it to appear on all pages or none, but I am unable to get it to display based on whether the challenge start date is before or after todays date. I believe it could be a date format issue, but everything I have tried has fallen short.
Here is my code:
Get todays date
$date_now = new dateTime();
Challenge start date
$challengeStartDate = date('dS F Y', strtotime($this->item->start_date));
echo '<!--' . strtotime('1970/1/1 00:00:00 +' . $validity) . '-->';
New text line
if ($challengeStartDate > $date_now) echo "New Text";
date() returns a string. With $challengeStartDate > $date_now it's like comparing if one string is bigger than the other (not sure if your dateTime handles that).
Your approach is otherwise fine. Just use timestamps to compare. time() gets you the time as a Unix timestamp:
$now = time();
if ($now > strtotime($this->item->start_date)) {
// do your thing
}
Something like this is more what you need. Try it out.
I had the very same problem some time ago.
All you need to do is store your local time in a database so it would be saved statically.
Because in your example, both $challengeStartDate and $date_now will change and update simultaneously and you wiill always get the current pc time!
Try storing it in a table or idk maybe sessions would help too.

How do you get the "last modified" date from a file in the correct time zone?

So I am trying to get the Last Modified date of a file in PHP, I am using this:
$file = "my_file.txt";
$date = date("F j, Y H:i:s.", filemtime($file));
Now the problem is when I echo it, I do not get it in my timezone.
It comes up in UTC time, but I am in UTC-4 timezone.
(e1:) How do I get it to show my timezone, or even (e2:) display it in the timezone for whoever is viewing the webpage?
Example 1: Lets say I update the file at 1pm (UTC-4). Anyone looking at the webpage will see it displayed as 1pm (UTC-4) regardless of where they are located.
Example 2: Say I update the file at 1pm (UTC-4), and someone from the timezone UTC is looking at my webpage; they will see the time 5pm (UTC), because that's the time I uploaded it in their timezone.
Get the server time from PHP and store it in an HTML element. (There are other ways to pass the data, but this one is pretty easy to understand.) Here, I just used the time() function to grab the current time. Your filemtime method should return a timestamp if you omit the formatting options.
Then, grab the timestamp from the <div> with JS. Since the JS want milliseconds, multiply it by 1000. Then use toLocalString() to offset it to the user's local time.
<div id="timeholder" data-time="<?php echo json_encode(time()); ?>"></div>
<script type="text/javascript">
var date = new Date(document.getElementById('timeholder').dataset.time * 1000).toLocaleString();
console.log(date);
</script>
For Example 1:
Thanks to #thingEvery for doing the math on how much I needed to subtract from the current timestamp.
$filetime = date("U", filemtime($pfile));
$hoursToSubtract = 4;
$timeToSubtract = ($hoursToSubtract * 60 * 60);
$mytime = $filetime - $timeToSubtract;
# I needed to print it in two different formats,
# that's why I split it up
$time1 = date("F j, Y", $mytime);
$time2 = date("g:i A [e-4]", $mytime);

How to get local time in php?

I am trying to get the local time using php. I wrote two different versions, but they both give the wrong time
date_default_timezone_set('UTC');
$now = new DateTime();
echo $now->getTimestamp();
Another way
date_default_timezone_set('America/New York');
echo strtotime("now")."<br/>";;
$now = new DateTime();
echo $now->getTimestamp();
In both cases I get the time 4 fours ahead of my local time. There is any other way to get the local time?
DateTime::getTimestamp() returns unix timestamp. That number is always UTC. What you want is format the date according to your time zone.
$dt = new DateTime("now", new DateTimeZone('America/New_York'));
echo $dt->format('m/d/Y, H:i:s');
Or use a different date format, according to what you need.
Also, you can use DateTime library for all your date needs. No need to change server's default timezone every time you want to fetch the date.
Simply use function date_default_timezone_set(). Here is example:
<?php
date_default_timezone_set("Asia/Dhaka");
echo date('d-m-Y h:i:s A');
?>
Hope it will help,
Thanks.
You need to use javascript because you want the value of time from the client. PHP is a server-side language that evaluates on the server and sends results to the client. So if you try to pull a date/time using a PHP function, it's going to pull the date from the server, which is not always in the client's timezone.
You can do this in a javascript function and then reference the value in the display.
var thisDateTime = new Date();
If you don't want to use timezone you can use this mix of windows and php commands:
<?php
$D = exec('date /T');
$T = exec('time /T');
$DT = strtotime(str_replace("/","-",$D." ".$T));
echo(date("Y-m-d H:i:s",$DT));
?>
I'm wondering why nobody has mentioned localtime(time()); in PHP with indexed key array result or localtime(time(), true); with associative key array result.
For the record, I found the only solution to read the real hour of the machine is to read the information outside of PHP (javascript, shell or other processes). Why?
For example, let's say we have an hour based in daily-saving. What if the timezone of the OS (Windows in my case) is not in sync with the timezone of PHP, I mean, it could be calculated differently. Or maybe the machine is using a different hour and it is ignoring the daily-saving hour.
Right now, my zone is UTC -4 Santiago 9:35 pm (with daily saving). However, PHP considers as 10:35 PM (using localtime,time,date and DateTime).
If anyone here wanted to get the local time according to the user's timezone (dynamically), then you can consider the following code:
$ip = $_SERVER['REMOTE_ADDR'];
$ipInfo = file_get_contents('http://ip-api.com/json/' . $ip);
$ipInfo = json_decode($ipInfo);
$timezone = $ipInfo->timezone ?? "UTC";
$dt = new DateTime("now", new DateTimeZone($timezone));
echo $dt->format('Y-m-d H:i:s');
The above code will get the user's local timezone and print the time according to that.
If you wanted to test the above code on your localhost then make sure to hard code your IP address there because the API can't provide you the timezone based on your local address (127.0.0.1), but the above code works fine on the
live server.
For Localhost, do:
$ip = '-------'; //your IP address
You can solve this problem by using localtime() function or through date_default_timezone_set() function.
Learn more about the localtime() function reffer:
http://php.net/manual/en/function.localtime.php
or
Learn more about the date_default_timezone_set() function reffer http://www.php.net/manual/en/function.date-default-timezone-set.php
i think this must help you..

PHP Time mismatch between date() and time()

I want to insert user entry log in a database table. The column where I want to keep the current date time is "date_time decimal(10,0) NOT NULL DEFAULT '0'". When inserting data I set the field as
$this->mytable->date_time = time();
My query executed successfully. But when I want to display the time of the entry it shows the time which is not match my pc(local server) time. To display the time I write
echo date('Y-m-d h:i:s A', $log->date_time);
I test several times but it showing the time which is 4 hours less than the exact time. On my test the current time is 2013-09-15 04:46:34 PM but table row shows 2013-09-15 12:46:34 PM.
Please help me. I can not find out the mistake.
You need to specify the timezone. The time() function will just retern a timestamp which is timezone-independent.
When you use the date() function you are using the server's timezone, I would recommend using the DateTime object:
$timezone = new DateTimeZone("Etc/GMT-4");
$date = new DateTime("#".$log->date_time); // #-symbol indicates timestamp input
$date->setTimezone($timezone);
echo $date->format("r");
Here is a list of supported timezones http://php.net/manual/en/timezones.php
Sorry. It was my mistake. When inserting data I set the time zone as
if(function_exists('date_default_timezone_set')) date_default_timezone_set("Asia/Dhaka");
But when display the data I forgot to set the time zone. It working fine when I set the time zone as I defined before in my display page. Thanks everybody for your help.
Try this
<?php
date_default_timezone_get();
echo time();
Manual

Changing PHP default timezone not working

I am trying to have a line of code added to an html document that is preceded by the time. I want the time zone to be relative to me, however I cannot change it from the default UTC. I have changed in the php.ini file to PST as well as using date_default_timezone_set('America/Los_Angeles'); and yet it still prints the time 7 hours ahead of my timezone. Heres the code that deals with the time:
session_start();
if(isset($_SESSION['name']))
{
date_default_timezone_set('America/Los_Angeles');
$msg = $_POST['text'];
$fo = fopen("log.html", 'a');
fwrite($fo, "<div class=msgln>(".date("g:i A").") <b style=color:red;>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($msg))."<br></div>
");
fclose($fo);
}
Servers should be set to UTC, and you should not be looking to change the default. Instead, what you want to do is create a DateTime object based on the time, then convert it to the timezone you want, and display.
$now = new DateTime();
$now->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $now->format('g:i A');
I don't know if your format string is valid or not, but the format method is suppossed to be compatible with that accepted by the date() function you were using in your original example.
First make sure you're using a valued timezone. You can find a list of supported timezones in the PHP docs.
The second problem is using date() without specifying the timestamp. This defaults to the timestamp produced by time() which (based on a comment in the documentation) is UTC time. You'll either have to use strftime() or manually subtract the difference from UTC.
If you use 'etc/GMT' you can set the dateTime object to the desired time zone like so:
$dtz = new DateTimeZone('etc/GMT-10');
$dt = new DateTime(date("Y-m-d h:i A"), $dtz);
$date = gmdate("Y-m-d h:i A", $dt->format('U'));

Categories