how can I get my system timezone on my php server - php

My machine has (GMT +6:00 Astana,Dhaka) .I set my time zone on my php script
date_default_timezone_set('Asia/Dhaka');
But some times it shows wrong date in date() function. May be my php server doesn't set GMT time.
But My mysql server catch my machine system timezone. so I need same in php.
Here my database tables outline
SHOP_BALANCE-------------shop_balance_id(PK,AI,INT),shop_balance(DOUBLE),dates(DATE)
PRODUCT_PURCHASE_ITEM----product_purchase_item_id(PK,AI,INT),product_id(INT),
pr_pur_cost_price(DOUBLE),pr_pur_unit_price(DOUBLE),
quantity(INT),product_size(INT),dates(TIMESTAMP),
bool_check(TINYINT)
PRODUCT_PURCHASES--------product_purchase_id(PK,AI,INT),insert_operation(INT),
product_purchase_item_id(FK ref of PRODUCT_PURCHASE_ITEM).
product_id(INT),dates(TIMESTAMP),product_size(INT)
IDEA IS IF DATE MATCH, SHOP BALANCE DECREASING ON THIS DAY. IF DATE IS NEW DATE TO SHOP BALANCE LAST DATE, SHOP BALANCE ALSO DECREASING BUT INSERT NEW DATE
Here my code
Find last row mysql date on shop_balance table. My dates column is date type
$query=$this->db->query("select dates from shop_balance order by dates desc limit 1");
$rowfind_last_stock=$query->row();
if(isset($rowfind_last_stock->dates)){
$find_last_date=$rowfind_stock->dates;
}
Find today date in my php server
$today=date("Y-m-d");
Check date for different query
if($find_last_date==$today){
//run update query
$this->db->query(
"UPDATE
shop_balance AS s
INNER JOIN
(
SELECT p.dates,SUM(pr_pur_cost_price*quantity) AS net
FROM product_purchase_item AS i
LEFT JOIN product_purchases AS p
ON p.product_purchase_item_id=i.product_purchase_item_id
WHERE p.insert_operation='$id'
GROUP BY p.insert_operation
) AS a
ON s.dates=date(a.dates)
SET s.shop_balance=s.shop_balance-a.net
);"
}
else{
//run insert query
$this->db->query(
"INSERT INTO shop_balance
SELECT null,
(
(
SELECT shop_balance
FROM shop_balance
ORDER BY shop_balance_id
DESC LIMIT 1
)
-
(
SELECT p.dates,SUM(pr_pur_cost_price*quantity) AS net
FROM product_purchase_item AS i
LEFT JOIN product_purchases AS p
ON p.product_purchase_item_id=i.product_purchase_item_id
WHERE p.insert_operation='$id'
GROUP BY p.insert_operation
)
),
curdate();"
);
}
The problem is sometimes it perform insert query even same date in php and mysql date when I install different.Both timezone I set above GMT +6.00 . why this problem?

Please refer to the documentation MySQL Server Time Zone Support and for the time_zone and system_time_Zone variables.
I believe you will find that your system time zone setting is not what you expect. When your insert query calls curdate(), MySQL delivers it in the time zone from the session's time_zone variable. By default, this will be the same zone that is set in the system_time_zone variable.
You can check your time zone variables like this:
SHOW VARIABLES LIKE '%time_zone'
If you don't want to change the MySQL server's system time zone, then you can set the session time zone by inserting this before your queries:
SET time_zone = 'Asia/Dhaka';
If you get an error, then the time zone tables haven't been loaded. You can use the mysql_tzinfo_to_sql to populate them. See also this answer.
Of course, a much easier solution would be to not use curdate(), and instead gather the current date from PHP and pass it in to query as a parameter.

Note that since PHP 5.1.0 (when the date/time functions were rewritten), every call to a date/time function will generate a E_NOTICE if the timezone isn't valid, and/or a E_WARNING message if using the system settings or the TZ environment variable.
Instead of using this function to set the default timezone in your script, you can also use the INI setting date.timezone to set the default timezone.

I am using this function.
function currentDate($dateOnly = false, $tillEnd = false)
{
// gmmktime(0, 0, 0, 7, 1, 2000) H i s m d Y
if($dateOnly)
{
if($tillEnd)
{
$t = explode('-',date('Y-m-d'));
return date('Y-m-d',mktime(23, 59, 59, $t[1], $t[2],$t[0]));
}else{
return date('Y-m-d');
}
}else{
if($tillEnd)
{
$t = explode('-',date('Y-m-d'));
return date('Y-m-d H:i:s',mktime(23, 59, 59, $t[1], $t[2],$t[0]));
}else{
return date('Y-m-d H:i:s');
}
}
}
You can call this function to get the time of the system.
Arguments are optional, If you want to get the current date with time then call as
eg:
$currentDatetime=currentDate();

time()
By this you can get time of system
Manual

Try this
<?php
$date = new DateTime(null, new DateTimeZone('Europe/London'));
$tz = $date->getTimezone();
echo $tz->getName();
?>

Related

Check if the time is more than 24h and show it

I have in my MSSQL database a column with datatype of datetime which contains some dates in this format 2021-01-11 19:58:04.277.
This is a voting system, the idea is that the users can only vote once every 24 hours.
Every time they vote this table is updated with a new record and a new date is added with the corresponding user.
I want to display a message that says how many hours left to place the next vote.
This is the code I am trying to use:
/**
* Get Votes Time
*
*/
public function getVoteRemainingTime($account) {
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$sql = "SELECT VoteDate FROM dbo.vote WHERE Account = :account ORDER BY logid DESC";
$query = $this->db->prepare($sql);
$query->execute(array(':account' => $account));
$voteDate = $query->fetch(PDO::FETCH_OBJ);
$timeLeftVote = strtotime($currentTime) - strtotime($voteDate->VoteDate);
if($timeLeftVote > 86400) {
return '<strong>Vote Available!</strong>';
} else {
return $timeLeftVote;
}
}
But it is displaying the wrong information. What I am doing wrong? I would appreciate your help.
Thanks!
you need declare format parameter of the date() like date('Y-m-d H:i:s')
date_default_timezone_get();
$currentTime = date('Y-m-d H:i:s');
$timeLeftVote = strtotime($currentTime) - strtotime('2021-01-11 19:58:04.277');
if($timeLeftVote > 86400){
echo 'Vote available';
}else{
echo $timeLeftVote;
}
Instead of SELECT VoteDate FROM dbo.vote
Can you do the calculation on the time difference at source in the database using
SELECT VoteDate, DATEDIFF(HOUR, VoteDate, GETDATE()) as HourDifference from dbo.vote
As I cannot check your database query, I only checked the rest of the code and it seems to work (as Fikri F mentioned in the comments of this post) if I replace $voteDate->VoteDate by a static date.
So please provide more information. You could output the current time and the previous vote time from the database as strings, and for both dates as well the result of strtotime, and in the end the result of the method. Then please explain, what the wrong behaviour is. By this, we can narrow down the problem either to the DB query or to the PHP code.
(I would write this as a comment, but I have not enough reputation.)

Time Calculations with MySQL

I'm writing a time logging programme for a client who is a piano tuner, and I've written the following PHP code to give a record a status of 'to do':
$last_tuned = '2017-01-05';
$tuning_period = 3;
$month_last_tuned = date('Y-m', strtotime(date('Y-m-d', strtotime($last_tuned))));
$next_tuning = date('Y-m', strtotime($month_last_tuned.(' +'.$tuning_period.' months')));
if (time() > strtotime($next_tuning.' -1 months')) {
if (time() > strtotime($next_tuning)) {
return 'late';
} else {
return 'upcoming';
}
}
As you can see, the $last_tuned variable is of the date(YYYY-MM-DD) format. This is then converted to a (YYYY-MM) format.
Once convered, an additional number of months, identical to $tuning_period is then added to the $month_last_tuned variable giving us a month and year value for when we need to add a new record.
If the current time (found with time()) is greater than the $next_tuning variable - 1 month, it returns that the task is upcoming. If it's after the $next_tuning variable, it returns that the task is late.
I now have to write a MySQL query to list the items that would return as upcoming or late.
How would I write this in MySQL? I'm not very good with MySQL functions, and some help would be much appreciated.
My attempt at the logic is:
SELECT * FROM records
// The next lines are to get the most recent month_last_tuned value and add the tuning_period variable
WHERE
NOW() > (SELECT tuning_date FROM tunings ORDER BY tuning_date ASC LIMIT 1)
+
(SELECT tuning_period FROM records WHERE records.id = INITIAL CUSTOMER ID)
I know that that is completely wrong. The logic is pretty much there though.
My database schema is as follows:
I expect the rows returned from the query to be on-par with the 'late' or 'upcoming' values in the PHP Code above. This means that the rows returned will be within 1 months of their next tuning date (calculated from last tuning plus tuning period).
Thanks!
You'd probably be better off with using the DateTime object instead of manipulating date strings.
$last_tuned = '2017-01-05';
$tuning_period = 3; // months
$dt_last_tuned = DateTimeImmutable::createFromFormat('Y-m-d',$last_tuned);
$dt_next_tuning = $dt_last_tuned->add(new DateInterval('P3M'));
$dt_now = new DateTimeImmutable();
$dt_tuning_upcoming = $dt_next_tuning->sub(new DateInterval('P1M'));
if( $dt_now > $dt_next_tuning) {
return 'late';
}
if( $dt_now > $dt_tuning_upcoming) {
return 'upcoming';
}
You can also use these DateTime objects in your MySQL queries, by building the query and passing through something like $dt_next_tuning->format('Y-m-d H:i:s'); as needed.
Given your table structure, however, it may be easier to just get all the relevant records and process them. It's a little difficult to tell exactly how the pieces fit together, but generally speaking MySQL shouldn't be used for "processing" stuff.

php date timezone issue

I have PHP site which is running with some custom script. I store a last query date in the DB as UTC, like this:
$query = "UPDATE mytable SET last_query = UTC_TIMESTAMP() WHERE id = 1";
When the script executes, it grabs that last date and converts it to the local tz like this:
$sql = "SELECT last_query FROM mytable WHERE id = 1"; // grab date
$result = $dbo->query($sql);
$row = $result->fetch();
$last_query = new DateTime($row['last_query'], new DateTimeZone('UTC')); // build datetime
$last_query->setTimezone(new DateTimeZone('America/Denver')); // set to local tz
$last_query = $last_query->format('Y-m-d\TH:i:s'); // format
$this->log('info', "Last queried: ".$last_query);
In my phpinfo(), date.timezone = America/Denver but the line for Default timezone shows UTC.
I have an older logging script that prints a log line preceded by the date produced using date, like this: $time = date( $this->DateFormat );
The problem is that in the log file, it shows the last query date as incorrect:
2016-07-05 12:00:02 - INFO --> Last queried: 2016-07-05T18:00:02
The date of the log message (2016-07-05 12:00:02) is correct-- the date of the last_query as you can see is 6hrs ahead (or UTC time).
What am I missing in my date conversion (or possibly in the PHP ini?) that is causing this mismatch? I'm assuming that I'm wrong to instantiate the DateTime object with the UTC timezone, but despite reading a lot of documentation on timezones I am still unclear.
EDIT: the last_query column is a mysql TIMESTAMP field

not able to post in custom time zone

$usersTimezone = new DateTimeZone('America/Vancouver');
$l10nDate = new DateTime($date);
$l10nDate->setTimeZone($usersTimezone);
$msg_time = $l10nDate->format('h:i A M d',time());
Not sure where is the mistake... if i put $msg_time = date('h:i A M d',strtotime($row["date_time"])); everything is working but my server time and my country time is not the same. so I need to post data in db in my own time zone to calculate.
On top of your PHP files, add this
date_default_timezone_set('America/Vancouver');
Or in your MySQL INSERT you can add this, that is if you use current_timestamp
SET time_zone = 'America/Vancouver';

get date from database and check if this date has passed

I have a database that holds jobs. It holds the job name and the expiration date. My database is user_job(id, user_id, job_name, day, month, year). The form that used in order to insert expiration date for the job in database included 3 drop-down lists. One that the user selected day(values 1-31) then month(values jan to dec) and year(2014 to 2024). I use the following function to get server's date:
<?php
$server_date = date('Y-m-d');
$a = mysql_query("select * from `user_job` where `user_id`='$session_user_id' ");
while($run_job = mysql_fetch_array($a)){
$the_job_day = $run_job['day'];
$the_job_month = $run_job['month'];
$the_job_year = $run_job['year'];
}
?>
My question is if there is a possibility now to compare server's date with the job's expiration date in my database. And if expiration date has passed just to echo a message, "expired". Is there a posibility to do this?
$the_job_time = strtotime($the_job_year .'-'. $the_job_month .'-'. $the_job_day);
$current_time = time();
if ($current_time > $the_job_time) {
// the job have expired
}
But I would suggest to store the time differently in the database. There are a bunch of different date/time types you can use
There is more than one way to do it, by order of effectiveness :
Store your date as a date column in you database, then use a select statement to compare with NOW()
Get the current timestamps and the timestamps of you job, then compare them.
Use the DateTime class of PHP to use the DateTime::diff() method (see the documentation)

Categories