Converting dates with PHP for DATETIME in SQL - php

I have a forum in PHP which takes a date like in the form
dd/mm/yyyy hh:mm:ss. However, I need to insert it for SQL as a DATETIME in the format as yyyy-mm-dd hh:mm:ss. How can I convert this data?

Your date time format is wrong: dd/mm/yyyy hh:mm:ss. Probably you mean d/m/Y H:i:s
If you have 5.3+ version there is safe way to convert the date time into another format. Here's an example:
$timestamp = '31/05/2001 12:22:56';
$timestamp = DateTime::createFromFormat('d/m/Y H:i:s', $timestamp);
echo $timestamp->format('Y-m-d H:i:s');
or if you like more procedural way:
$timestamp = '31/05/2001 12:22:56';
$timestamp = date_create_from_format('d/m/Y H:i:s', $timestamp);
echo date_format($timestamp, 'Y-m-d H:i:s');
Be careful with previous suggestions. Some are completely wrong and others could lead to errors.

You can use the strtotime and date to rework the format.
$new_date = date( "Y-m-d H:i:s", strtotime( $old_date ) );
What this does is take your old date (dd/mm/yyyy hh:mm:ss), converts it to a unix timestamp that can then be used with the php date function to format the date to the desired format.

Two of several possible ways:
Convert in code and then pass the converted value to mysql: $mysqldate = date( 'Y-m-d H:i:s', $phpdate );
Let mysql do the work by using its built-in functions:
$query = "UPDATE table SET datetimefield = FROM_UNIXTIME($phpdate) ...";

if you have datetime avaialable from a from like above format then u just need to use following function.
function localToMysql($dateTime){
$date_chunks = explode('/', $dateTime);
$time_chunks = explode(' ', $date_chunks[2]);
$final_format = $time_chunks[0] . "-" . $date_chunks[1] . "-" . $date_chunks[0] . " " . $time_chunks[1];
return $final_format;
}

Related

How can I set numbers that equals days of month [duplicate]

I have a datetime column in MySQL.
How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?
If you're looking for a way to normalize a date into MySQL format, use the following
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.
The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format.
(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)
To convert a date retrieved from MySQL into the format requested (mm/dd/yy H:M (AM/PM)):
// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM
Refer to the PHP date formatting options to adjust the format.
If you are using PHP 5, you can also try
$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");
$valid_date = date( 'm/d/y g:i A', strtotime($date));
Reference: http://php.net/manual/en/function.date.php
Finally the right solution for PHP 5.3 and above:
(added optional Timezone to the Example like mentioned in the comments)
without time zone:
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date);
echo $date->format('m/d/y h:i a');
with time zone:
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone('Europe/Berlin'));
echo $date->format('m/d/y h:i a');
An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.
If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.
Forget all. Just use:
$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))
To correctly format a DateTime object in PHP for storing in MySQL use the standardised format that MySQL uses, which is ISO 8601.
PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.
$dtNow = new DateTime();
$mysqlDateTime = $dtNow->format(DateTime::ISO8601);
This, and a list of other PHP DateTime constants are available at http://php.net/manual/en/class.datetime.php#datetime.constants.types
This should format a field in an SQL query:
SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
Use the date function:
<?php
echo date("m/d/y g:i (A)", $DB_Date_Field);
?>
Depending on your MySQL datetime configuration. Typically: 2011-12-31 07:55:13 format. This very simple function should do the magic:
function datetime()
{
return date( 'Y-m-d H:i:s', time());
}
echo datetime(); // display example: 2011-12-31 07:55:13
Or a bit more advance to match the question.
function datetime($date_string = false)
{
if (!$date_string)
{
$date_string = time();
}
return date("Y-m-d H:i:s", strtotime($date_string));
}
SELECT
DATE_FORMAT(demo.dateFrom, '%e.%M.%Y') as dateFrom,
DATE_FORMAT(demo.dateUntil, '%e.%M.%Y') as dateUntil
FROM demo
If you dont want to change every function in your PHP code, to show the expected date format, change it at the source - your database.
It is important to name the rows with the as operator as in the example above (as dateFrom, as dateUntil). The names you write there are the names, the rows will be called in your result.
The output of this example will be
[Day of the month, numeric (0..31)].[Month name (January..December)].[Year, numeric, four digits]
Example: 5.August.2015
Change the dots with the separator of choice and check the DATE_FORMAT(date,format) function for more date formats.
You can also have your query return the time as a Unix timestamp. That would get rid of the need to call strtotime() and make things a bit less intensive on the PHP side...
select UNIX_TIMESTAMP(timsstamp) as unixtime from the_table where id = 1234;
Then in PHP just use the date() function to format it whichever way you'd like.
<?php
echo date('l jS \of F Y h:i:s A', $row->unixtime);
?>
or
<?php
echo date('F j, Y, g:i a', $row->unixtime);
?>
I like this approach as opposed to using MySQL's DATE_FORMAT function, because it allows you to reuse the same query to grab the data and allows you to alter the formatting in PHP.
It's annoying to have two different queries just to change the way the date looks in the UI.
You can have trouble with dates not returned in Unix Timestamp, so this works for me...
return date("F j, Y g:i a", strtotime(substr($datestring, 0, 15)))
This will work...
echo date('m/d/y H:i (A)',strtotime($data_from_mysql));
Using PHP version 4.4.9 & MySQL 5.0, this worked for me:
$oDate = strtotime($row['PubDate']);
$sDate = date("m/d/y",$oDate);
echo $sDate
PubDate is the column in MySQL.
Direct output e.g. in German format:
echo(date('d.m.Y H:i:s', strtotime($row["date_added"])));
$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";

What is datatype of date? [duplicate]

I have a datetime column in MySQL.
How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?
If you're looking for a way to normalize a date into MySQL format, use the following
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.
The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format.
(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)
To convert a date retrieved from MySQL into the format requested (mm/dd/yy H:M (AM/PM)):
// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM
Refer to the PHP date formatting options to adjust the format.
If you are using PHP 5, you can also try
$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");
$valid_date = date( 'm/d/y g:i A', strtotime($date));
Reference: http://php.net/manual/en/function.date.php
Finally the right solution for PHP 5.3 and above:
(added optional Timezone to the Example like mentioned in the comments)
without time zone:
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date);
echo $date->format('m/d/y h:i a');
with time zone:
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone('Europe/Berlin'));
echo $date->format('m/d/y h:i a');
An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.
If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.
Forget all. Just use:
$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))
To correctly format a DateTime object in PHP for storing in MySQL use the standardised format that MySQL uses, which is ISO 8601.
PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.
$dtNow = new DateTime();
$mysqlDateTime = $dtNow->format(DateTime::ISO8601);
This, and a list of other PHP DateTime constants are available at http://php.net/manual/en/class.datetime.php#datetime.constants.types
This should format a field in an SQL query:
SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
Use the date function:
<?php
echo date("m/d/y g:i (A)", $DB_Date_Field);
?>
Depending on your MySQL datetime configuration. Typically: 2011-12-31 07:55:13 format. This very simple function should do the magic:
function datetime()
{
return date( 'Y-m-d H:i:s', time());
}
echo datetime(); // display example: 2011-12-31 07:55:13
Or a bit more advance to match the question.
function datetime($date_string = false)
{
if (!$date_string)
{
$date_string = time();
}
return date("Y-m-d H:i:s", strtotime($date_string));
}
SELECT
DATE_FORMAT(demo.dateFrom, '%e.%M.%Y') as dateFrom,
DATE_FORMAT(demo.dateUntil, '%e.%M.%Y') as dateUntil
FROM demo
If you dont want to change every function in your PHP code, to show the expected date format, change it at the source - your database.
It is important to name the rows with the as operator as in the example above (as dateFrom, as dateUntil). The names you write there are the names, the rows will be called in your result.
The output of this example will be
[Day of the month, numeric (0..31)].[Month name (January..December)].[Year, numeric, four digits]
Example: 5.August.2015
Change the dots with the separator of choice and check the DATE_FORMAT(date,format) function for more date formats.
You can also have your query return the time as a Unix timestamp. That would get rid of the need to call strtotime() and make things a bit less intensive on the PHP side...
select UNIX_TIMESTAMP(timsstamp) as unixtime from the_table where id = 1234;
Then in PHP just use the date() function to format it whichever way you'd like.
<?php
echo date('l jS \of F Y h:i:s A', $row->unixtime);
?>
or
<?php
echo date('F j, Y, g:i a', $row->unixtime);
?>
I like this approach as opposed to using MySQL's DATE_FORMAT function, because it allows you to reuse the same query to grab the data and allows you to alter the formatting in PHP.
It's annoying to have two different queries just to change the way the date looks in the UI.
You can have trouble with dates not returned in Unix Timestamp, so this works for me...
return date("F j, Y g:i a", strtotime(substr($datestring, 0, 15)))
This will work...
echo date('m/d/y H:i (A)',strtotime($data_from_mysql));
Using PHP version 4.4.9 & MySQL 5.0, this worked for me:
$oDate = strtotime($row['PubDate']);
$sDate = date("m/d/y",$oDate);
echo $sDate
PubDate is the column in MySQL.
Direct output e.g. in German format:
echo(date('d.m.Y H:i:s', strtotime($row["date_added"])));
$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";

Mysql format date to insert to table

I need to format and insert the date to mysql table which is type of datetime, I am doing this from php.
Here is the statement
$timestamp ="22-11-2015+00:00:00";
$mysqltime = date ("d-m-Y H:i:s", $timestamp);
But when I insert to table the date is wrong, it showing 31-12-1969 19:00:22
What could be the issue?
It should be
$timestamp ="22-11-2015+00:00:00";
$mysqltime = date ("d-m-Y H:i:s", strtotime($timestamp));
because date is expecting it's second parameter to be a number, specifically the number of seconds since midnight January 1st, 1970.
The date function expects an integer timestamp for the second argument.
This MSQL insert statement would work fine:
INSERT INTO mytable (birthday) ('2015-11-22 00:00:00')
If you're using a database class in PHP and the function you're calling is using a PHP date object, then you'd have to construct the PHP date object using the date() function.
Or if you want to use PHP code to reformat the date in PHP before sending the string to the database to be inserted, then I think you'd use strtodate to get a PHP date object, and then date()
$phpdate = strtodate('d-m-Y H:i:s', '22-11-2015 00:00:00')
$dateformysql = date('Y-m-d H:i:s', $phpdate)
databaseclass.dotheinsert($mysqldate)
This should be working, but did not work for me!
$timestamp ="22-11-2015+00:00:00";
$mysqltime = date ("d-m-Y H:i:s", strtotime($timestamp));
I believe it is because my national standard format (LC_TIME) is "Y-m-d" rather then "d-m-Y". However this works perfectly:
$timestamp ="22-11-2015+00:00:00";
// The '+' sign needs to be escaped!!
$time = date_create_from_format( "d-m-Y\+H:i:s", $timestamp);
$mysqltime = $time->format( 'd-m-Y H:i:s' );
On the other hand, MySQL use the date format "YYYY-MM-DD" as a standard. The correct format string should be:
$mysqltime = date ("Y-m-d H:i:s", strtotime($timestamp));
// or second option
$mysqltime = $time->format( 'Y-m-d H:i:s' );
I think the corret format would be:
$mysqltime = date_format ($timestamp,"d-m-Y H:i:s");
Let me know if this works

converting between date formats

how would you convert a date stored as
2011-01-18 11:51:41
into
18-01-2011 11:51:41
using PHP?
many thanks in advance!
date('d-m-Y H:i:s', strtotime('2011-01-18 11:51:41'));
More reliable than using strtotime(), assuming you're on PHP 5.3+
$oldtime = date_parse_from_format('Y-m-d h:i:s', '2011-01-18 11:51:41');
$newtime = date('d-m-Y h:i:s', $time);
However, the date format you're converting FROM suggests it's coming from a MySQL datetime field, in which case you could also do:
SELECT DATE_FORMAT(yourfield, '%d-%m-%Y %H:%i:%s')
and save yourself a full roundtrip in PHP.
Convert the old date to UNIX time with strtotime(), then output it in the new format with date()
$olddate = "2011-01-18 11:51:41";
$newdate = date('d-m-Y H:i:s', strtotime($olddate));
echo $newdate;
// 18-01-2011 11:51:41
$your_date = "2011-01-18 11:51:41";
echo date('d-m-Y H:i:s', strtotime($your_date));
demo

Convert from MySQL datetime to another format with PHP

I have a datetime column in MySQL.
How can I convert it to the display as mm/dd/yy H:M (AM/PM) using PHP?
If you're looking for a way to normalize a date into MySQL format, use the following
$phpdate = strtotime( $mysqldate );
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
The line $phpdate = strtotime( $mysqldate ) accepts a string and performs a series of heuristics to turn that string into a unix timestamp.
The line $mysqldate = date( 'Y-m-d H:i:s', $phpdate ) uses that timestamp and PHP's date function to turn that timestamp back into MySQL's standard date format.
(Editor Note: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)
To convert a date retrieved from MySQL into the format requested (mm/dd/yy H:M (AM/PM)):
// $datetime is something like: 2014-01-31 13:05:59
$time = strtotime($datetimeFromMysql);
$myFormatForView = date("m/d/y g:i A", $time);
// $myFormatForView is something like: 01/31/14 1:05 PM
Refer to the PHP date formatting options to adjust the format.
If you are using PHP 5, you can also try
$oDate = new DateTime($row->createdate);
$sDate = $oDate->format("Y-m-d H:i:s");
$valid_date = date( 'm/d/y g:i A', strtotime($date));
Reference: http://php.net/manual/en/function.date.php
Finally the right solution for PHP 5.3 and above:
(added optional Timezone to the Example like mentioned in the comments)
without time zone:
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date);
echo $date->format('m/d/y h:i a');
with time zone:
$date = \DateTime::createFromFormat('Y-m-d H:i:s', $mysql_source_date, new \DateTimeZone('UTC'));
$date->setTimezone(new \DateTimeZone('Europe/Berlin'));
echo $date->format('m/d/y h:i a');
An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.
If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.
Forget all. Just use:
$date = date("Y-m-d H:i:s",strtotime(str_replace('/','-',$date)))
To correctly format a DateTime object in PHP for storing in MySQL use the standardised format that MySQL uses, which is ISO 8601.
PHP has had this format stored as a constant since version 5.1.1, and I highly recommend using it rather than manually typing the string each time.
$dtNow = new DateTime();
$mysqlDateTime = $dtNow->format(DateTime::ISO8601);
This, and a list of other PHP DateTime constants are available at http://php.net/manual/en/class.datetime.php#datetime.constants.types
This should format a field in an SQL query:
SELECT DATE_FORMAT( `fieldname` , '%d-%m-%Y' ) FROM tablename
Use the date function:
<?php
echo date("m/d/y g:i (A)", $DB_Date_Field);
?>
Depending on your MySQL datetime configuration. Typically: 2011-12-31 07:55:13 format. This very simple function should do the magic:
function datetime()
{
return date( 'Y-m-d H:i:s', time());
}
echo datetime(); // display example: 2011-12-31 07:55:13
Or a bit more advance to match the question.
function datetime($date_string = false)
{
if (!$date_string)
{
$date_string = time();
}
return date("Y-m-d H:i:s", strtotime($date_string));
}
SELECT
DATE_FORMAT(demo.dateFrom, '%e.%M.%Y') as dateFrom,
DATE_FORMAT(demo.dateUntil, '%e.%M.%Y') as dateUntil
FROM demo
If you dont want to change every function in your PHP code, to show the expected date format, change it at the source - your database.
It is important to name the rows with the as operator as in the example above (as dateFrom, as dateUntil). The names you write there are the names, the rows will be called in your result.
The output of this example will be
[Day of the month, numeric (0..31)].[Month name (January..December)].[Year, numeric, four digits]
Example: 5.August.2015
Change the dots with the separator of choice and check the DATE_FORMAT(date,format) function for more date formats.
You can also have your query return the time as a Unix timestamp. That would get rid of the need to call strtotime() and make things a bit less intensive on the PHP side...
select UNIX_TIMESTAMP(timsstamp) as unixtime from the_table where id = 1234;
Then in PHP just use the date() function to format it whichever way you'd like.
<?php
echo date('l jS \of F Y h:i:s A', $row->unixtime);
?>
or
<?php
echo date('F j, Y, g:i a', $row->unixtime);
?>
I like this approach as opposed to using MySQL's DATE_FORMAT function, because it allows you to reuse the same query to grab the data and allows you to alter the formatting in PHP.
It's annoying to have two different queries just to change the way the date looks in the UI.
You can have trouble with dates not returned in Unix Timestamp, so this works for me...
return date("F j, Y g:i a", strtotime(substr($datestring, 0, 15)))
This will work...
echo date('m/d/y H:i (A)',strtotime($data_from_mysql));
Using PHP version 4.4.9 & MySQL 5.0, this worked for me:
$oDate = strtotime($row['PubDate']);
$sDate = date("m/d/y",$oDate);
echo $sDate
PubDate is the column in MySQL.
Direct output e.g. in German format:
echo(date('d.m.Y H:i:s', strtotime($row["date_added"])));
$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";

Categories