PHP Time mismatch between date() and time() - php

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

Related

Default time zone in php

I am trying to save the current date and time and i have used the following code
Current PHP version: 5.4.16
date_default_timezone_set('Asia/Kolkata');
$datet = date("Y-m-d H:i:s ");
When i echo it the output will be
2017-04-25 05:07:17
But actual time what i need is
2017-04-25 10:45:17
I have tried using now() but its also showing the same date rather than the current time, In what ways i can get the Current date and time. Any help appreciated.
have you tried to change the server time, print date on console, if this mismatched, then change the server time.
Check This
This gives you correct time after setting default time zone "Asia/Kolkata"
date_default_timezone_set("Asia/Kolkata");
echo date("Y-m-d h:i:s");
Please check my attachment. Here, First of all I have check
echo date_default_timezone_get();` and getting my default timezone Asia/Calcutta and after that when I changed timezone as
date_default_timezone_set("Asia/Bangkok");
echo date_default_timezone_get();
Asia/Bangkok
enter image description here

A Need To Check For Daylight Saving Time

What i am trying to archive is what time exactly a post was posted based on the users default timezone via there IP.
What i am worried about is daylight saving time so say if it's 1:46PM now then if daylight saving time in effect it might still post a update as 1:46PM instead of the exact time 3:46PM
The question is does PHP automatically check against that? or is there anything I need to do to see if daylight saving is in effect or not
$timezone = '+0:00';
$timezone = preg_replace('/[^0-9]/', '', $timezone) * 36;
$timezone_name = timezone_name_from_abbr(null, $timezone, true);
date_default_timezone_set($timezone_name);
echo date('D d M Y H:i:s');
Thanks :)
Just checking as everything needs to be 100% accurate
The answer is yes, PHP can give you the precise time based on timezone, regardless of DST. For example, if a user's IP tells you that they're in New York, you could do
$date = date_create('now America/New_York');
to create a DateTime object with the current time in New York.
echo $date->format('h:i:s');
Incidentally, DST is currently in effect, and this code prints the correct current time of 12:21:32.
EDIT
In response to your follow-up question, yes, the time that you save is the time that you will retrieve. For example,
$timestamp = (int) $date->format('U');
would save the absolute unix time of 12:21:32 (or whenever you run this code), regardless of timezone or DST. Another DateTime object will yield the same time:
$retrieved = new DateTime;
$retrieved->setTimestamp($timestamp);
echo $retrieved->format('h:i:s'); // outputs '12:21:32'
Hope that helps.
EDIT 2
To answer your next question, it is indeed possible to adjust a DateTime you've saved to a different timezone. First, set your script's default timezone to UTC.
date_default_timezone_set('UTC');
Then, you can save your timestamps as shown above (except, don't specify a timezone), and when you retrieve them, you can adjust them to where your users are:
echo $retrieved->format('h:i:s'); // Outputs UTC time of 5:21:32
$retrieved->setTimezone(new DateTimeZone('America/New_York'));
echo $retrieved->format('h:i:s'); // Outputs correct New York time of 12:21:32
Even after DST ends, this code would still display 12:21:32 (or, again, whatever time at which you run it)
Hope that helps, again!
EDIT 3
To address your most recent question, you can always just adjust the DateTime object based on the user's settings. For example, if they decide to override DST to off, then you should
// Change your default timezone to that of your user
date_default_timezone_set('America/New_York');
// Check for daylight savings time with date('I')
if (date('I', $timestamp) == 1) $retrieved->modify('-1 hour');
And that should do it!

timestamp from both date & time inputs and compare php

I've been struggling to get an exact answer for this question. There are many that are close to what I'm wanting but seem to still be just off. The application of this is to ensure that a booking can't be made for a past date.
I have a form which has an input for time & another for date. Firstly, I wan't to take both of these inputs & convert them to a timestamp.
This code returns nothing
$time_date = sprintf("%s %s", $pDate, $pTime);
$objDate = DateTime::createFromFormat('H:ia d/m/Y', $time_date);
$stamp = $objDate->getTimestamp();
echo $stamp;
So I've have tried using something like this
$pDate = $_POST['pDate'];
$pTime = $_POST['pTime'];
$full_date = $pDate . ' ' . $pTime;
$timestamp = strtotime($full_date);
echo $timestamp;
But for some reason it is returning an incorrect timestamp. (i've been using an online converter) 02/06/2014 as date & 12:23am as time, is not 1401625380. This according to the converter is Sun, 01 Jun 2014 12:23:00 GMT.
Does someone have working code for returning a timestamp of both time & date inputs?
Secondly I want to compare this timestamp with a specified one & check to see if it is greater than. I've created a timestamp for my timezone with this
$date = new DateTime(null, new DateTimeZone('Pacific/Auckland'));
$cDate = $date->getTimestamp();
echo $cDate;
and will simply have an if statement which compares the two and echos the appropriate message.
I feel as though there are multiple question on here that are ALMOST what I'm wanting to achieve but I can't manage to get them working. Apologies for the near duplicate.
Note: I'm using ajax to post form data (if this could possibly interfere).
Your second code snipped is correct. Assuming it's in datetime format (Y-m-d H:i:s).
From php manual about strtotime():
Each parameter of this function uses the default time zone unless a time zone is specified in that parameter.
Check your PHP default time zone with date_default_timezone_get() function.
To compare two dates, be sure they both are in same time zones.
For datetime inputs I personally use jQuery UI timepicker addon.
you receiving the time and date in string format - so i don't believe the ajax can interfere.
as for your question:
first of all - find out what is the locale timezone of your server. you can do it by this function: date_default_timezone_get.
if the answer doesn't suit you - you can use its "sister": date_default_timezone_set, and change it to whatever value you need (like 'Pacific/Auckland' - see the documentation there). it is also recommended to return it to the original value after you finish your stuff.
i believe fixing your locale timezone will solve your issue.

advice with php date and timestamps

We have a battle system where people can pick a match time to challenge another player. To create a match the user needs to pick a date. Currently a user picks the day, hour, minute, and pm/am from a dropdown list. If the user selects 5/20/2012 # 1PM, the system adds the hours and minutes from the start of the day. Here's a quick sample to get a better understanding of what I'm talking about:
$time = strtotime('today', $inputdate);
$time = $time + $hours + $minutes;
the value of $hours changes if the users selects AM or PM. It's pretty basic:
Everything was working fine until people started have timezone issues. For example, if player A creates a match at 1:PM, then player B will see the match starts at 1:PM, but he/she will have different timezones!
The problem is that I don't know the problem :/
I don't know how to fix the timezone issue. I have been creating functions in the hopes that everything will fall together, but no luck.
What I have:
User profiles have a timezone options.
A function that gets the raw timestamp and returns the formatted time based on the user's timezone.
A function that gets a timestamp and converts it to another timestamp
based on the user's timezone.
I'm lost and I can't seem to fix the issue, I can code, but right now I'm not thinking logical. I took me one hour to write this and try to explain it how I could, since I myself don't know how to make it work. Some advice is appreciated.
I need a function to convert a timestamp to UTC-5:
function input_date($timestamp)
{
global $vbulletin;
$timestamp = (int)$timestamp;
if (strlen((string)$timestamp) == 10)
{
$hour = 3600.00;
$offset = $vbulletin->userinfo['timezoneoffset'];//sample -8
$ds = (int)$vbulletin->userinfo['dstonoff'];//DST
$fluff = $hour*($offset+5.00);
$timestamp = $timestamp+$fluff+($ds*$hour);
return $timestamp;//return timestamp in UTC-5 format..
}
else
{
return 0;
}
}
Essentially everything in the database should be stored using a single timezone, preferably one which is not affected by DST. The standard option here is UTC.
If you know the user's timezone by its name, you can use that to generate your time:
// Player A creates match at 1PM Europe/London
$timezone = 'Europe/London';
$localTime = '2012-03-01 13:00:00';
// work out UNIX timestamp using that timezone (making it timezone independent)
date_default_timezone_set($timezone);
$timestamp = strtotime($localTime);
// store $timestamp in the database
// Player B views the timestamp with timezone America/Los_Angeles
$timezone = 'America/Los_Angeles';
date_default_timezone_set($timezone);
var_dump(date('c', $timestamp)); // see manual for more output formats
If you have the timezones stored as their abbreviations (e.g. "CET", "GMT"), then use timezone_name_from_abbr to get the correct timezone name.

PHP Datetime Error

I am having an issue with php date() function.
When I save the date in mysql datebase the hours shows 4 hours less than my current time.
My php code is below: $add_date = date("Y-m-d H:i:s");
It saves the time in database as
2011-08-03 07:51:26
But is should show
2011-08-03 13:22:26
Can anybody tell me how to fix it
Thanks
You have to set a valid time zone - it seems you don't have an appropriate time zone set up in php environment for your location.
Check out
http://www.php.net/manual/en/function.date-default-timezone-set.php
It should give you a clue how to set up the correct time zone in php.
#Mujahid If the printed time and the saved time are the same it probably means your server is not in the same timezone as you. With that said, you have to manually set the default timezone for your PHP script at the top of the file, or get the DateTime by defining your timezone explicitly. Here's the code:
$dateTime = new DateTime("now", new DateTimeZone('America/Los_Angeles'));
$add_date = $dateTime->format("Y-m-d H:i:s");
echo $add_date;
Here's a list of time zones that PHP supports, just find yours and replace America/Los_Angeles with it.
http://php.net/manual/en/timezones.php
Here's a good tutorial on PHP DateTime and DateTimeZone...
http://ditio.net/2008/06/03/php-datetime-and-datetimezone-tutorial/
Hope this helps. Good luck.
Make the time zone setting of the MySQL server and the web server the same.
this will add hosted server time not local time
$add_date = date("Y-m-d H:i:s");
use strtotime() to add hours and minutes
$newdate = date("Y-m-d H:i:s",strtotime('+ 5 hours 30 minutes'.$row['db_date']));

Categories