Errors with using a timestamp in PHP - php

I am receiving the error: A non well formed numeric value encountered
Here is my code:
<?php
$timestamp= '2013-01-20 18:20:20';
$datetime= date('F j, Y', $timestamp);
echo $datetime;
?>
This returns January 1, 1970 Which isn't right. What am I doing wrong?
BTW: All of my $timestamp variables will be in that format. I am using datetime in my MySQL database table.
Thanks

the date function takes a timestamp which is an int
you need to call it using
date('F j, Y', time());
or
$timestamp= '2013-01-20 18:20:20';
date('F j, Y', strtotime($timestamp));
see http://php.net/manual/en/function.date.php for info on how to use the date function

'2013-01-20 18:20:20' is not a timestamp . You have to convert it to timestamp. You can use strtotime function to do this.
$timestamp= strtotime('2013-01-20 18:20:20');

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'])))."'";

Formatting time() in PHP

I'm using a database where in the table I have the time after it was saved using time()
Is there any way formatting it to human readable way (date and time)?
Thanks
yes, you can use date function for that.
echo date("F j, Y, g:i a", $timestamp);
Output will be in following format:
// March 10, 2001, 5:16 pm
you use this query:
SELECT DATE_FORMAT(timestamp, '%M %d, %Y %h:%i:%s %p') as mydate
see DATE_FORMAT for more info
Check here
PHP Date() Documentation
There's a table with every option
An example:
date('Y m d')
prints
2013 07 19
If you have trouble with the data displaying from some of the other answers there is also this function strtotime which may help parse it.
echo date("F j, Y, g:i a", strtotime($timestamp));
After querying the database for the timestamp, pass it through the function formatTime. This creates a new DateTime object in php called $data that can also easily be manipulated if you need. The examples below formats the date in two different ways, both work.
Procedural Style:
function formatTime($millis) {
$date = new DateTime($millis);
return date_format($date, 'l, jS F Y \a\t g:ia');
}
Object Oriented Style:
function formatTime($millis) {
$date = new DateTime($millis);
return $date->format('l, jS F Y \a\t g:ia');
}
The format for date can be found at this link:
http://php.net/manual/en/function.date.php
Cheers!

Simple PHP date question

I have the following string:
$date = 2011-08-29 14:53:15;
when I do this:
echo date('F j, Y', $date);
I get December 31, 1969 instead of August 29, 2011. How to get the right date?
Use strtotime on your $date value.
echo date('f j, Y',strtotime($date));
<?php
$date = strtotime($date);
echo date('F j, Y', $date);
?>
To explain...
The function date() is expecting a unix time-stamp (something like 23498034). the function strtotime() takes a normal looking date that a person would make, and converts it to a timestamp. Then you're good to go.

Converting time in PHP?

How do i convert the time which I pull from a database 2009-09-27 23:58:54 to the following time using PHP Sep 27, 2009.
<?php echo date('M j, Y', strtotime('2009-09-27 23:58:54')); ?>
If you're using MySQL then I would advise you use the MySQL date_format() function, something like this:
SELECT date_format(date, '%b %e,%Y') AS `formatted_date` FROM `table_name`;
In PHP you can use strtotime or in MySQL you can use UNIX_TIMESTAMP to get the date into a timestamp.
You can then use the date function to format it as you want:
$timestamp = strtotime($myDate);
$dateStr = date('M j, Y', $timestamp);

Categories