PHP/MySQL: Convert from YYYY-MM-DD to DD Month, YYYY? - php

I have in a MySQL table a DATE column that represents the date in this format: YYYY-MM-DD.
I wanto to retrieve the date from the database using PHP but display it like this: DD Month, YYYY.
From '2009-04-13' to '13 April, 2009' for example.
Witch is the best way to do it?? ( I know how to get the date from the DB. I only need to know how to convert it)
I also need to display the month names in Spanish. There is a way to do it without translating each month using strplc or something like that??
I'm new to programming, please be detailed.
Thanks!!!

Refer to DATE_FORMAT() function in MySQL. I guess that's the best way for you to do it.
Also, you can make this:
Fetch your date from DB
Use strtotime in PHP, to convert to unix time
Then format the time using date.
By using date() you'll be able to get months names in Spanish when you set your locale in PHP with setlocale.

You could also skip the strtotime() part by using UNIX_TIMESTAMP(date) in your MySql select. But remember that this is a MySQL specific function and may not be be portable in the future.

Execute following MySQL queries:
SET lc_time_names = 'es_ES';
SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...
With MySQLi it'll be:
$mysqli->query("SET lc_time_names = 'es_ES'");
$stmt = $mysqli->prepare("SELECT DATE_FORMAT(t.date,'%e de %M, %Y') FROM your_table t ...where id = ?");
...

Another option not yet mentioned:
SQL:
SELECT UNIX_TIMESTAMP(date) FROM table
PHP:
print date('your format', $timestamp_from_the_db);

Personally, I like to use integer data types in MySQL for date storage in the UNIX timestamp format. I leave all the processing of that integer up to PHP. Keeping tables and queries as simple as possible has always served me well. Predominantly, in the code I write, dates have some sort of calculation done to them. This is all done on the PHP side and always in the UNIX timestamp format. Storing or retrieving the dates in anything other than the UNIX timestamp format just means another step for errors to creep in and makes the query less modular. How a date is formatted is best left up until the last minute before it's displayed. It's just my opinion, but unless there are extreme circumstances where you can't process the DB value after extraction, a date shouldn't be formatted SQL-side.
A simplified example:
<?php
$date = now();
$dueDate = $date + 60*60*24*7; // One week from now
$sqlInsert = "INSERT INTO reports SET `dueDate` = $date";
$resInsert = mysql_query( $sqlInsert );
$sqlSelect = "SELECT `dueDate` FROM reports";
$resSelect = mysql_query( $sqlSelect );
$rowSelect = mysql_fetch_array( $resSelect );
$DB_dueDate = $rowSelect['dueDate'];
$daysUntilDue = ( $DB_dueDate - now() ) / 60*60*24;
$formattedDueDate = date( "j F, Y", $DB_dueDate );
?>
The report is due on <?=$formattedDueDate?>. That is <?=$daysUntilDue?> from now.

Simplest way is to use the strtotime() function to normalize the input to UNIX timestamp.
Then use the date() function to output the date in any format you wish. Note that you need to pass the UNIX timestamp as the second argument to date().

This will help you to convert as you want:
$dob ='2009-04-13';
echo date('d M Y', strtotime($dob));

$origDate = "2018-04-20";
$newDate = date("d-m-Y", strtotime($origDate));
echo $newDate;

Related

Display human readable time from EPOCH time - PHP

I have a epoch time in my MySql table
------------
update_time
------------
1401362621
1401362864
I want to convert this time to a human readable format. I have written in my select query, which is not working.
$sql = "SELECT UNIX_TIMESTAMP(update_time) FROM table_name";
Use the date function:
$t=1401362621; // your time here
echo date('Y-m-d H:i:s', $t); // format your date
You can use other formatting options like what here:
http://php.net/manual/en/function.date.php
you can do that either in php or in mysql way:
Its upto you to choose :
Mysql way:
SELECT FROM_UNIXTIME(update_time) FROM table_name";
see the doc: Mysql date and time function
PHP way:
echo date('Y-m-d H:i:s', '1401362864');

Format DATETIME from MYSQL database using PHP

So I have a field in my database called 'DateTime' and the following lines of code:
echo "Date/Time: ";
echo $row['DateTime'];
How do I format it so that instead of being like this:'2013-02-07 22:14:56', it will be like this: '07/02/13 - 22:14'
Thanks.
Alternatively you could use:
DateTime::createFromFormat('Y/m/d H:i:s',$row['DateTime']); this will give you a datetime object, which are quite nice to work with.
Another alternative would be to have MySQL format the DATETIME value as a string in the desired format, using the DATE_FORMAT function.
SELECT DATE_FORMAT(`DateTime`,'%d/%m/%y - %H:%i') AS `DateTime`
...
No change required to your PHP code except for the SQL text sent to the database server.
This approach can very efficient, and reduce the amount of code you need, if all you are doing with this string is displaying it. If you are doing any sort of manipulation on this value, then casting the string value returned from MySQL resultset into a datetime object is probably a better way to go.
A demonstration of the DATE_FORMAT function:
SELECT DATE_FORMAT('2013-02-07 22:14:56','%d/%m/%y - %H:%i') AS `DateTime`
DateTime
----------------
07/02/13 - 22:14
how to output date into Year textbox Month textbox Day textbox
$book_date = $myrow["Publication_Day"];
$book_year = Date("Y", strtotime($book_date));
$timestamp contains ur date & time in any format.....................
date('Y/m/d - H:i',strtotime($timeStamp));
echo date('d/m/y H:i', strtotime($row['DateTime']));
See date and strtotime for more detail on the functions from the docs
$mytime = strtotime('2013-06-07 22:14:56');
$newDate = date('m/d/y - G:i', $mytime);
echo $newDate;
Here's an alternative using DateTime. If you're working with timezones this code can be easily modified to handle that.
$datetime = new DateTime('2013-02-07 22:14:56');
echo $datetime->format('d/m/y H:i');
See it in action

between operator for timestamps in mysql query

I have a form to pick up dates from calender. That form will pass start date and end date. My database table stores date in time-stamp format. I have to create a query to pick records from database table between start date and end date. How can I make a query? I have tried the code below, but which is not working.
if(isset($_POST['filter']))
{
$sid=$_POST['sid'];
$start= date("dMY",strtotime($_POST['start']));
$end= date("dMY",strtotime($_POST['end']));
$res=$db->fetchAll("SELECT * FROM `logfile` WHERE `site_id`=".$sid." AND (date('dMY',`timestamp`) BETWEEN $start AND $end)");
}
Any thoughts?
Thanks.
You're forcing PHP and MySQL to do a lot of useless date/time string<->native conversions for no reason.
Why not simply have:
$start = strtotime($_POST['start']);
SELECT ... WHERE `timestamp` BETWEEN FROM_UNIXTIME($start) AND ...
if $_POST['start'] and $_POST['end'] are already in timestamp format, just don't change them. In other case just convert the string in timestamp:
$start = strtotime($_POST['start']); // where $_POST['start'] might be 2012/08/07
$end = strtotime($_POST['end']);
$res=$db->fetchAll("SELECT * FROM logfile WHERE site_id=".$sid." AND date BETWEEN $start AND $end");
As #Matei Mihai said you don't need to convert $_POST['start'] and $_POST['end'] to timestamp format and you must enclose date columns in quotes.
Also you need to convert date in MySQL compatible format like '2012-08-01'.
"SELECT *
FROM `logfile`
WHERE `site_id`=".$sid." AND
(date('dMY',`timestamp`) BETWEEN '$start' AND '$end')");

PHP to MySQL date formatting issue

I have a PHP/MySQL date formatting problem. Here, i create the date variables:
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
Then i insert it to a mysql table with the column Datatype of bigint.
When i then, later on, when i need to echo the date, i use this code:
echo '<td>'.date("d/m/y H:i",$row['f_uploaded_date']).'</td>';
But istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
Can anyone explain why this is happening, and how to fix it?
Thank you in advance,
Adam
When you insert it into the MySQL table do it like this:
INSERT INTO yourtable(something,somedate) VALUES('something',str_to_date('".$checkDate."','%d/%m/%y %H:%i'))
and when you pull it out from MySQL then do it like this:
SELECT *,date_format(somedate,'%D/%M/%Y %H:%i') as formateddate from yourtable
then in php you use:
$row['formateddate']
Hope it helps you :)
EDIT:
The complete code:
$ddate = date("d/m/y H:i", time());
$sql = "INSERT INTO files (rowID, file, mimetype, data, uploaded_by, uploaded_date, size, times_downloaded, description) VALUES (NULL, '$fileName', '$fileType', '$content', '$user', str_to_date('".$ddate."','%d/%m/%y %H:%i'), $fileSize, 0, '$description')";
So you convert a unix timestamp into a formatted date string then convert the formatted time string back into a unix timstamp and insert that into your database. Wouldn't it just be simpler to just insert the unix timestamp you got in the first place? Or not even bother with PHP code and
INSERT INTO sometable (id, f_uploaded_date)
VALUES ($id, UNIX_TIMESTAMP(NOW()))
?
I suspect the explicit problem you describe is due to the fact that strtotime expects date strings of format 99/99/9999 to be the american style of mm/dd/yyyy rather than dd/mm/yyyy as used in the UK.
First,
$checkDate = date("d/m/y H:i", time());
$datestrto = strtotime($checkDate);
is quite funny way of assigning time() frunction result to $datestrto variable.
Next, you don't need that variable either, as you just can use unix_timestamp() mysql function in the insert query.
Now to your question.
istead of echo'ing the date in the format D/M/Y H:i, it echo'es the date in the format of m/d/y H:i.
double-check your syntax. there is a typo somewhere.
You can pull a date format from your mysql database and then when converting to a php variable you can use:
$num=mysql_numrows($result);
$i=0;
while ($i <= $num) {
$date=mysql_result($result,$i,"Date");
$date = date('d-m-Y', strtotime($date));
echo $date."<br>";
}
Where $result is your mysql query result and "Date" is the name of the column. However I am unsure of using this method with the time.
--EDIT--
link: http://php.net/manual/en/function.date.php

PHP - Formatting HH:MM:SS to 12hr HH:MM:a string

I'm hoping this will be a piece of pie for someone! String output is currently 12:00am for everything.
The following code from MySQL with format HH:MM:SS (hours_open, hours_closed)
$get_hours_sql = "SELECT * FROM client_hours ORDER BY day";
$get_hours_res = mysqli_query($dbConnect, $get_hours_sql) or die(mysqli_error($dbConnect));
// Establish the output variable
$hoursList = '<div class="right_bar">';
while ($productList = mysqli_fetch_array($get_hours_res)) {
$id_hours = $productList['id_hours'];
$day = $productList['product_name'];
$open = $productList['hours_open'];
$close = $productList['hours_close'];
$hoursList .= ''.date("g:ia", $open).' - '.date("g:ia", $close).'<br/>';
}
$hoursList .= '</div>';
echo $hoursList;
Output is currently
12:00am - 12:00am
looped.
I want to get the output to
11:00am - 11:00pm
which would represent the database entries.
Thanks!
I always find PHP <-> MySql date handling fiddly (got better with 5.3 though).
My guess is that the mysql query returns the date as a string and date() is expecting a time stamp.
Often, I just get mysql to format the date as a string for me and return it as an additional field, like so:
$get_hours_sql = "SELECT *,date_format(hours_open,'%h:%i %p') as hours_open_formatted, date_format(hours_close,'%h:%i %p') as hours_close_formatted FROM client_hours ORDER BY day";
then just use the formatted fields:
$hoursList .= ''.$productList['hours_open_formatted'].' - '.$productList['hours_close_formatted'].'<br/>';
Data accepts as it's second parameter a Unix timestamp, so what you're trying to do simply won't work. You could use either mysql's TIME_TO_SEC function, or php's mktime to convert the time string to a Unix timestamp.
Example:
$openHours = explode(':',$productList['hours_open']);
$timestamp = mktime($openHours[0],$openHours[1]);
$yourDate = date("g:ia",$timestamp);
Edit: I think you should try Ben's answer, I think it's a better solution than mine.

Categories