I'm trying to save events into my table that contain date_start and date_end timestamps. From another PHP page, I get four inputs: two date inputs and two time inputs. I'm trying to insert these values but I keep getting the following value on inserting it:
0000-00-00 00:00:00
Here's my script:
$rep=$bdd->query('SELECT * FROM association WHERE nom="'.$_SESSION['usertag'].'"');
$data=$rep->fetch();
$debut="\'".$_POST['date_start']." ".$_POST['time_start'].":00\'";
$fin="\'".$_POST['date_end']." ".$_POST['time_end'].":00\'";
$debut=date('Y-m-d H:i:s');
$fin=date('Y-m-d H:i:s');
$timestamp_debut =strtotime($debut);
$timestamp_fin = strtotime($fin);
$req=$bdd->query('INSERT into evenement values (NULL,'.$_POST['name'].','.$_POST['content'].',\''.$timestamp_debut.'\',\''.$timestamp_fin.'\','.$data['id'].')');
PHP's strtotime() outputs a Unix timestamp. If your database column type is DATETIME, a Unix timestamp is not the correct format. You can just insert the formatted date() string.
For example:
strtotime(date('Y-m-d H:i:s'))
1562117846
date('Y-m-d H:i:s')
2019-07-02 21:36:40
For MySQL:
MySQL recognizes DATETIME and TIMESTAMP values ... [a]s a string in either 'YYYY-MM-DD hh:mm:ss' or 'YY-MM-DD hh:mm:ss' format. A "relaxed" syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012#12#31 11^30^45' are equivalent.
String and Numeric Literals in Date and Time Context
However, it seems that you're using the current timestamp when you might want to use the values posted from your form. PHP's date() uses "the current time if no timestamp is given".
If you want to use your posted values instead, you can indeed use strtotime() to convert them to Unix timestamps and then date() to format them.
$date = '2019-07-02';
$time = '15:28';
date('Y-m-d H:i:s',strtotime($date.' '.$time));
2019-07-02 15:28:00
Alternatively, I might recommend using PHP's DateTime class:
$date = '2019-07-02';
$time = '15:28';
$datetime = new Datetime($date.' '.$time);
echo $datetime->format('Y-m-d H:i:s');
2019-07-02 15:28:00
Related
I am using DateTime function of php. I get a date from a calendar in format d-m-Y and pass it via ajax to my function. I am getting the date right till this step.
When I try to store the date in unix format using:
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y', $data['date']);
$final_date=$ai_ff_date->format('U');
The date stored is wrong. Suppose the date I passed via ajax is 26-12-2016 then in database 27-12-2016 is stored. Why its counting one more day then the input.
use this code :
$date = date('Y-m-d H:i:s', strtotime('-1 day', $stop_date));
$ai_ff_date=DateTime::CreateFromFormat('d-m-Y',$date);
$final_date=$ai_ff_date->format('U');
and please check the variable (code not tested)
You might want to convert the Date-Format to "Y-m-d" First and then call-in the DateTime() Constructor. However, since what you are trying to do is just get the TimeStamp you might also do that directly without using DateTime. The Snippet below shows what is meant here:
<?php
$data = ['date'=>"13-12-2016"]; //<== JUST AN EXAMPLE FOR TESTING!!!
// SIMPLY CONVERT THE DATE TO Y-m-d FIRST.
$dateYMD = date("Y-m-d", strtotime($data['date']));
// THEN USE DateTime CONSTRUCTOR TO CREATE A NEW DateTime INSTANCE
// AND THEN RUN THE FORMAT YOU WISH::
$final_date = (new DateTime($dateYMD))->format('U');
var_dump($final_date); //<== YIELDS: string '1481583600' (length=10)
var_dump(date("Y-m-d", $final_date)); //<== YIELDS: string '2016-12-13' (length=10)
I have a loop and in it the date is coming in different formats like for some values it will be like '10-13-2013 04:31' and for some it is like '2013-10-14T22:14:40-0700'. I tried to store this in DB as the value of a datetime/timestamp column but it is failing for the first format that is 10-13-2013 04:31. So I tried to convert it into UNIX timestamp using strtotime(). It is working for some values and is storing zero for values like '10-13-2013 04:31'. I think this is because it is considering the second value as month and so failing. My code is as follows :
foreach($reports as $report){
echo strtotime($report->transactionDate);
}
strtotime() is unable to parse mm-dd-yyyy format. Instead you should use DateTime::createFromFormat(), like this:
$date = '10-13-2013 04:31';
$obj = DateTime::createFromFormat('m-d-Y H:i', $date);
$date = $obj->format('Y-m-d H:i:s');
I have the following problem. I have a string, which contains time and date as follows:
dd/MM/yy hh:mm:ss
This I have in PHP. And then I have a MySQL database, which has a column of a datetime format, where I need to insert this value. Obviously the problem is, that the format is different, so instead of the actual date, it results in a field "0000-00-00 00:00:00".
Could you please help me with converting this string and then inserting it properly into MySQL?
For the MySQL I use the standard INSERT INTO command.
From the DATETIME documentation:
MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format.
I'd use PHP's DateTime class and DateTime::createFromFormat() method, and convert the data into a MySQL-compatible date string, like so:
$date = DateTime::createFromFormat('d/m/Y H:i:s', $yourDateString);
$dateToBeInserted = $date->format('Y-m-d H:i:s');
Write a function to convert date,
function sqldate($date)
{
$sql_date = date('Y-m-d H:i:s',strtotime($date));
return $sql_date;
}
And your query look like,
$query = "INSERT INTO tableName (dateColumn) VALUES('".sqldate($date)."') ";
You can convert it using STR_TO_DATE() along with your INSERT statement, eg.
INSERT INTO tableName (dateColumn)
VALUES(STR_TO_DATE('dd/MM/yy hh:mm:ss','%d/%m/%y %H:%i:%s'))
SQLFiddle Demo
Try this:
$parsedDate = date('Y-m-d H:i:s', strtotime($yourDate));
// Insert $parsedDate into your table column Date
In my UI the dates are shown like this - dd.mm.YYYY hh:ii:ss. The users are able to edit/add new dates and most probably they'll try to use the same format (24.06.2012 15:35:00) which can not be used for a SQL query. Here is what I've done till now:
$dt = (date_parse_from_format("d.m.Y H:i:s", $data['event_time']));
$newdate = sprintf("%02d-%02d-%04d %02d:%02d:%02d" , $dt['day'], $dt['month'], $dt['year'], $dt['hour'], $dt['minute'], $dt['second']);
$test = date("Y-m-d H:i:s", strtotime($newdate));
if ($test == "1970-01-01 01:00:00")
{
throw new Exception('Invalid date');
}
What happens is - if I leave the check if ($test == "1970-01-01 01:00:00") I get an exception, but if I comment the $test = date("Y-m-d H:i:s", strtotime($newdate)); line and the check the date is inserted only with zeros.
$newdate is a sting in the right format for SQL - YYYY-mm-dd H:i:s but obv. I miss something here. How to insert this string as a valid SQL datetime?
Thanks
Leron
The DateTime class was introduced in PHP 5.2 and would allow you to use something like this
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false){
throw new Exception("Invalid date");
}
DateTime::createFromFormat returns false on failure (This method is only available since PHP 5.3)
Then when saving to the database you can use the following to get the correct format for MySQL
$dt->format("Y-m-d H:i:s")
MySQL provides the FROM_UNIXTIME( ) and UNIX_TIMESTAMP( ) functions to convert a Unix timestamp to a MySQL date format, and vice versa.
$SqlString = "INSERT INTO table(mydate, content) VALUES (FROM_UNIXTIME($mydate), $content)";
UNIX_TIMESTAMP, if called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the
format YYMMDD or YYYYMMDD.
$SqlString = "SELECT *, UNIX_TIMESTAMP($mydate) AS mydate FROM table WHERE conId = $conId";
Take a deeper look at these MySql functions and also the mktime() function could help you.
I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?
Converting from timestamp to format:
date('Y-m-d', $timestamp);
Converting from formatted to timestamp:
mktime(0, 0, 0, $month, $day, $year, $is_dst);
See date and mktime for further documentation.
When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format. Check the MySQL Doc for TIMESTAMP info.
You can avoid having to use strtotime() or getdate() in PHP by using MySQL's UNIX_TIMESTAMP() function.
SELECT UNIX_TIMESTAMP(timestamp) FROM sometable
The resulting data will be a standard integer Unix timestamp, so you can do a direct comparison to time().
I wrote this little function to simplify the process:
/**
* Convert MySQL datetime to PHP time
*/
function convert_datetime($datetime) {
//example: 2008-02-07 12:19:32
$values = split(" ", $datetime);
$dates = split("-", $values[0]);
$times = split(":", $values[1]);
$newdate = mktime($times[0], $times[1], $times[2], $dates[1], $dates[2], $dates[0]);
return $newdate;
}
I hope this helps
strtotime() and getdate() are two functions that can be used to get dates from strings and timestamps. There isn't a standard library function that converts between MySQL and PHP timestamps though.
Use the PHP Date function. You may have to convert the mysql timestamp to a Unix timestamp in your query using the UNIX_TIMESTAMP function in mysql.
A date string of the form:
YYYY-MM-DD
has no time associated with it. A MySQL Timestamp is of the form:
YYYY-MM-DD HH:mm:ss
to compare the two, you'll either have to add a time to the date string, like midnight for example
$datetime = '2008-08-21'.' 00:00:00';
and then use a function to compare the epoc time between them
if (strtotime($datetime) > strtotime($timestamp)) {
echo 'Datetime later';
} else {
echo 'Timestamp equal or greater';
}