PHP - mktime store wrong date in mysql - php

When I store the date through FROM_UNIXTIME() the date stores one day before.
My debug code:
$date = date("m-d-Y", time());
$date_unix = explode('-', $date);
if (count($date_unix) == 3) {
list ( $m, $d, $y ) = $date_unix;
$date_unix = mktime(0, 0, 0, $m, $d, $y);
}
echo "<br />Date: " . $date;
echo "<br />Date after mktime: " . $date_unix;
echo "<br />Date manual mktime: " . date("m-d-Y", mktime(0,0,0,8,18,2014));
I'm using the date from the server, change it to a unixtime with mktime() and trying to store in the database with FROM_UNIXTIME().
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD);
$sql = "INSERT INTO data ( data ) VALUES ( FROM_UNIXTIME(:date_unix) )";
$st = $conn->prepare($sql);
$st->bindValue(":date_unix", $date_unix, PDO::PARAM_INT);
$st->execute();
And after all this mess, the mysql still stores the date in the day before.
Ex: today is 08/18/2014 and in the database is 2014-08-17
The date_default_timezone in the server is "America/Cuiaba" and nothing change if I change the timezone.

Unix timestamps are UTC by definition. However, MySQL's FROM_UNIXTIME implicitly converts a unix timestamp into the MySQL server's timezone (which is a completely different setting than PHP's default_date_timezone setting).
The America/Cuiaba timezone is UTC - 4 hours, so the date "2014-08-18 00:00:00 (UTC)" is actually 2014-08-17 20:00:00 (America/Cuiaba)" -- thus the apparent 1-day difference.
Have a look at this answer on how to convert between timezones in your MySQL database.

Related

Time stored in DB minus 2 weeks

I would like to show the date 2 weeks before the date stored in a DB
The date isnt stored in Timestamp, it is stored like 01/01/2015
I have tried the below but this isnt working, can anyone help?
echo date('$valid_to', strtotime("-2 week"));
I would use DateTime class instead.
// timezone is optional
$date = new DateTime($valid_to, new DateTimeZone('Europe/Vilnius'));
echo $date->modify('-2 weeks');
// there you have your wanted date
$valid_date = $date->format('Y-m-d');
Then would recommend STR_TO_DATE mysql function to convert to correct timestamp.
For example:
$query = "SELECT * FROM table WHERE time_col <= STR_TO_DATE('" . $valid_date . "', '%Y-%m-%d')";

How to compare EST date time with mysql data

I have purchase data in mysql database table. All data on server are stored in UTC timezone.
I can convert date-time in EST timezone using below code.
$date = date_create(date('Y-m-d H:i:s'), timezone_open('Etc/GMT+0'));
date_timezone_set($date, timezone_open('Etc/GMT+5'));
I am getting last and next Saturday of current day using below code.
$dt_week_start_time = strtotime("last saturday")+((20*3600)+ 1);
$dt_week_start_date = date('Y-m-d G:i:s', $dt_week_start_time);
$dt_week_end_time = $dt_week_start_time + (7*3600*24) - 1;
$dt_week_end_date = date('Y-m-d G:i:s', $dt_week_end_time);
But how can i compare above EST timezone converted date-time with mysql data stored in UTC timezone? I need to convert data of 'purchasedatetime' field in EST timezone when I fire below query. Is this possible? Or am I doing it in wrong way? Please advise.
$str_query_select = "SELECT *, SUM(extendedprice) AS gross_price FROM t_product_purchase ";
$str_query_select .= " WHERE purchasedatetime BETWEEN '".$dt_week_start_date ."' AND '".$dt_week_end_date."'";
$str_query_select .= " AND sellerpkid=1";
$str_query_select .= " GROUP BY purchasedatetime ORDER BY purchasedatetime DESC ";
You can see this:
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_convert-tz
or
SET time_zone = 'proper timezone';
being done once right after connect to database. and after this all timestamps will be converted automatically when selecting them.
in php you can do this:
$date = new DateTime($dt_week_start_date);
$date->setTimezone(new DateTimeZone('Europe/Moscow')); // based on your required zone
echo $date->format('Y-m-d H:i:s');
then use it in your sql.

Converting and Comparing Date

I came across a problem where when I strtotime date it gives me a value which is not equal to what I have in the database.
Example:
In the database I have this value
1398308880
Which is equal to this date
24/04/2014
So what I did is
$date = date('24/04/2014');
$date = strtotime($date);
Which gives me
1398297600
I can't understand, why is there a difference between both of them whereas they should be same value right? what am doing wrong here.
Consider the following:
$time = '1398308880';
echo date("Y-m-d H:i:s", $time);
// outputs 2014-04-23 22:08:00
echo '<br />';
echo mktime(22, 8, 0, 4, 24, 2014);
// outputs 1398395280
The timestamp is still different even when you account for the hour, minute and second. Why? I'm in a Chicago timezone. What timezone are you in? Or more importantly, is your database running in the same timezone as your PHP server?

PHP date returned incorrectly

I am pulling a date value from a MySQL DB formatted as 01/20/13 I am calling the PHP date function on this value returned to get what day of the week it is, so 01/20/13 is today's date which is Sunday but it keeps returning the value Wednesday. I have included the code below I am new to programming so this is probably a stupid error I am overlooking.
<?php
require '../TimeCard/DB.php';
try{
$stmt = $conn->prepare('SELECT `date` FROM `timeRecords` WHERE `employeeID`= 1 ');
$stmt->execute();
} catch(PDOException $e){
echo'ERROR: ' . $e->getMessage();
}
while($row = $stmt->fetch())
{
echo date("l", $row['date']) . "<br>";
echo $row['date'] . "<br>";
}
?>
Mysql does not store dates as m/d/y it stores them as Y-m-d you're mysql database will turn "01/20/13" into 0000-00-00.
However, if you are not using the date type, and storing as a string use
strtotime($row['date'])
use strtotime on your mysql stored date, then use the date function on it
$day = date('l',strtotime($row['date']));
try with strtotime()
echo date("l", strtotime($row['date'])) . "<br>";
The second argument to PHP's date() function is an integer timestamp. You'd have better luck using DateTime, eg
$dt = DateTime::createFromFormat('m/d/y', $row['date']);
echo $dt->format('l');
This gives you the added bonus of tailoring the date parser to match your source format rather than relying on strtotime() which definitely has its quirks such as treating dates with forward-slashes (10/12/13) as US (12th October) vs dates with hyphens (10-12-13) as EU (10th December)
Example here - http://codepad.viper-7.com/iVXxA1

strtotime php mysql

All I'm trying to do is make the php file accumulate the end date from the sub date. I don't understand why this strtotime function isn't working. My database stores dates as "Y-m-d".
here's the code:
//disguised for security reasons
$db = mysql_connect("*******", "*******","********");
mysql_select_db("*******",$db);
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date!=null", $db);
while ($gad = mysql_fetch_array($getad)) {
$id = $gad['id'];
$asd = $gad['annual_sub_date'];
$aedate_time = strtotime('+1 year', $asd);
$aedate = date("Y-m-d", $aedate_time);
mysql_query("UPDATE members SET annual_end_date='$aedate', annual_active='Y' WHERE id='$id'");
}
---------SOLVED IT---------
I went and played XBox Split/Second for a bit and then realised the issue. My mind went back to PHP/MySQL 101. I coded everything right except the "!=null" part.
//Wrong Way
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date!=null", $db);
//Correct Way
$getad = mysql_query("SELECT id, annual_sub_date FROM members WHERE annual_sub_date IS NOT NULL", $db);
Now everything works :) That's the issues you can expect coding at 5:01am.
The first argument to strtotime is an absolute or relative date as a string, the second argument is an integer timestamp. You're giving it a relative date (string) as the first argument and an absolute date (also string) as the second. You need to convert $asd to a timestamp using strtotime first.
$aedate_time = strtotime('+1 year', strtotime($asd));
BTW, you could do the whole date calculation and updating in SQL with a single query, no need to take the long way around through PHP.
It's because strtotime requires timestamp as second argument and not string date in Y-m-d.
Just try code snippet below to see what I ment.
$gad = array('annual_sub_date' => '2010-11-21');
// wrong
// $asd = $gad['annual_sub_date'];
// good; convert to timestamp
list($year, $month, $day) = explode('-', $gad['annual_sub_date']);
$asd = mktime(0, 0, 0, $month, $day, $year);
$aedate_time = strtotime('+1 year', $asd);
$aedate = date("Y-m-d", $aedate_time);
echo $aedate . "\n";

Categories