I need to convert a date in this format:
November 28, 2009
to a MySQL date format:
2009-28-11
What's the best method to convert the date using PHP?
Improvised from: http://www.bigroom.co.uk/blog/dates-in-php-and-mysql
$mysqldate = date( 'Y-m-d', strtotime( $phpdate ) );
// Example:
$phpdate = 'November 20, 2009';
$mysqldate = date( 'Y-m-d', strtotime( $phpdate ) );
echo $mysqldate;
// output: 2009-11-20
If you want a "date" to be converted to "DateTime" this is the best way =
// for example: you have a string with the following
$dateFormat = 'd/m/Y';
$dateString = '02/12/2019';
// you can easily create DateTime using
$dateTime = \DateTime::createFromFormat($dateFormat, $dateString);
As described in the php documentation for createFromFormat.
And to answer completely on your question:
echo $dateTime->format('y-m-d');
I like to use strtotime and the date function as follows:
$mysql_date = date("Y-m-d", strtotime($source_date));
There are two options you can use which are strtotime or preg_split and sprintf. I recommend you use strtotime. The structure goes like this:
$date = 'November 28 2009';
$sqldate = date('Y-m-d', strtotime($date));
Make sure the Y is capital so it reads as 0000 otherwise it will read 00.
Related
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'])))."'";
How can I just convert date part of datetime to timestamp?
For example in this datetime: 2018-02-26 20:30:00
I want timestamp of 2018-02-26 00:00:00.
If you prefer using the DateTime API you could also do:
$dateAndTime = '2018-02-26 20:30:30';
DateTime::createFromFormat('Y-m-d H:i:s', $dateAndTime)->setTime(0, 0)->getTimestamp();
If you use substr you only need to use strtotime once and no date.
Echo strtotime(substr("2018-02-26 20:30:00",0,10));
Or you can use explode:
Echo strtotime(explode(" ", "2018-02-26 20:30:00")[0]);
I explode on space and use the first item [0]
<?php
echo strtotime(date("Y-m-d",strtotime("2018-02-26 20:30:00"))." 00:00:00");
Here you go. Just use strtotime twice. Once to set your date and then the second to generate the timestamp.
strtotime() can be used to convert just about any human readable date string to a timestamp.
http://php.net/manual/en/function.strtotime.php
$str = '2018-02-26 20:30:30';
echo date('Y-m-d', strtotime($str)) . '<br>';
echo strtotime(date('Y-m-d', strtotime($str)));
An easy and best solution would be this one:
$datetime = '2018-02-26 20:30:00';
$new_date = strtotime( Date( 'Y-m-d', strtotime( $datetime ) ) );
Try this:
$date = "2018-02-26 20:30:00";
echo strtotime(date('Y-m-d 00:00:00', $date));
This outputs UNIX timestamp. You can remove strtotime to get gregorian calendar
I have a date, in the format yyyy-mm-dd that has been pulled from a MySQL database. This date is saved to a variable $myDate.
I want to save the date, three weeks before this variable's date, to a new variable called $otherDate. How can I do this (and ideally, change the format of the date at the same time)?
I tried:
$otherDate = date("l d F", strtotime("-3 weeks", $myDate));
but to no avail.
The best way to get your head around strtotime is to look at the doc page for it:
The format expected is int strtotime ( string $time [, int $now = time() ] )
And the parameters are defined as:
time
A date/time string. Valid formats are explained in Date and Time Formats.
now
The timestamp which is used as a base for the calculation of relative dates.
Therefore $otherDate = date("l d F", strtotime("-3 weeks", $myDate)); is not correct since $myDate is not an integer but a string in yyyy-mm-dd format.
You must pass the $myDate into the string with the -3 weeks modifier:
$otherDate = date("l d F", strtotime("$myDate -3 weeks"));
Or if you want to redefine $now within the strtotime parameters:
$otherDate = date("l d F", strtotime("-3 weeks", strtotime($myDate)));
I would however recommend using a DateTime object:
$otherDate = new DateTime($myDate);
$otherDate->sub(new DateInterval('P3W'));
echo $otherDate->format('l d F');
The second argument to strtotime() must be a timestamp, not a string, so
$otherDate = date("l d F", strtotime("-3 weeks", strtotime($myDate)));
But look at using DateTime objects instead
$date = new \DateTime( $myDate );
$otherDate = clone $date;
$otherDate->sub( new \DateInterval('P3W') );
echo $otherDate->format( 'l d F' );
Since I find procedural date manipulation ugly and constrictive, I'm going to suggest using PHP's awesome DateTime class.
$dt = new DateTime('2014-11-28');
$dt->modify('-3 weeks');
echo $dt->format('l d F');
Because you are using the strtotime wrong way.
Check this:
$otherDate = date("l d F", strtotime("2014-11-28 -3 weeks"));
echo $otherDate;
Output:
Friday 07 November
I've got an datetime string like this: 28-06-14 11:01:00
That's European for day 28, month 6, year 2014...
I'm trying to convert it to 2014-06-28 11:01:00 so that I can insert it into a database with field type datetime.
I've tried multiple things like this:
$datumHolder = new DateTime($data['datum'], new DateTimeZone('Europe/Amsterdam'));
$datum1 = $datumHolder -> format("Y-m-d H:i:s");
$datum2 = date( 'Y-m-d', strtotime(str_replace('-', '/', $data['datum']) ) );
$datum3 = DateTime::createFromFormat( 'Y-m-d-:Hi:s', $data['datum']);
This is the output I get:
datum1: 2028-06-14 11:01:00
datum2: 1970-01-01
And I get an error for datum3:
echo "datum3: " . $datum3->format( 'Y-m-d H:i:s'); . '<br />';
Call to a member function format() on a non-object
What am I doing wrong and how do I get this to work?
Your $datum3 method is correct way, you just have invalid input format.
Use:
$datum3 = DateTime::createFromFormat('d-m-y H:i:s', $data['datum']);
// $data['datum'] is '28-06-14 11:01:00'
$datetime = DateTime::createFromFormat('d-m-y H:i:s', $data['datum']);
// y is two digit representation of a year, while Y is full numeric representation of a year, 4 digits
echo $datetime->format('Y-m-d H:i:s');
$timestamp = strtotime('28-06-14 11:01:00');
$output = gmdate("Y-m-d H:i:s", $timestamp);
echo $output;
That will give you a hint or two ;)
I am using the date() function to display a timestamp from my databse.
$date = date( 'F jS', $news_items['date']);
I know the $news_items['date']; as they return in a YYYY-MM-DD 00:00:00 format.
But after the function call $date dispays as December 31st for all values.
$date = date('F jS', strtotime($news_items['date']));
Try that :)
That's because date() wants a timestamp and not a string. You're better of with something like this;
$dt = date_create($news_items['date']);
$date = date_format($dt, 'F jS');
Or in the object oriented way;
$dt = new DateTime($news_items['date']);
$date = $dt->format('F jS');
The correct syntax for date function is given in PHP manual as:
string date ( string $format [, int $timestamp ] )
As you can see the second argument is expected to be an integer, but you are feeding the function with a string.