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');
Related
I have a table in MYSQL database with a column db_date with type is datetime ex:2016-10-20 01:05:00
I use a PHP code to search different thing the date is one of them for that i use a date picker have the date like this 10/21/2016 m/d/Y
for that i use this to transform this form to the form in database
STR_TO_DATE('".$date."','%m/%d/%Y')
The Problem is that when i use db_date= STR_TO_DATE('".$date."','%m/%d/%Y') it give only the date that have hour and minutes and second 00:00:00
but i want all the date ex: if i choose 10/20/2016 i want all date with different time in database be selected
i tried to use the date function in mysql but i didn't have result
date(STR_TO_DATE('".$date."','%m/%d/%Y'))
And also i tried to use the DATE_FORMAT(STR_TO_DATE('".$date."','%m/%d/%Y'))
and i didn't have a result
the query will be like this $query=SELECT * FROM tbl_staff {$sql}
and this is the code
$q = array();
$sql = "";
if(isset($_POST['txt_date']) && !empty($_POST['txt_date'])){
$date = mysqli_real_escape_string($conn,$_POST['txt_date']);
$q[] = " db_date=STR_TO_DATE('".$date."','%m/%d/%Y') and db_status!='Done' AND db_status!='Cancelled'";
}
How can i solve this problem ?!
First of all you can use format in datapicker to customise the date :
$('#date').datepicker({format: 'yyyy-mm-dd'});
And for your sql query do (use date() for db_date)
$q[] = " DATE(db_date)= $date and db_status!='Done' AND db_status!='Cancelled'";
I have one page in that I have two textboxes where user will enter unix timestamp and datetime, I have to compare that both timestamp and datetime but in php the timezone giving different timestamp as per time zone so the code doesn't working in all places where time zones are different.
Please help on this I had used..
strtotime(),mktime(),getTimestamp() in php,
also used my sql for this..
SELECT UNIX_TIMESTAMP() but all are giving different time stamps.
$sql = "SELECT UNIX_TIMESTAMP('date time from text box') as timeStampfromdb";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$timeStampFromDateTime = $row["timeStampfromdb"];
}
if($timeStampFromDateTime == timestamp textbox value)
{
matched
}
else
{
not matched
}
You can set php timezone in php.ini file, for GMT you need "GMT".
You can also try in your code:
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
date_default_timezone_set('GMT');
echo date('Y-m-d H:i:s T', time()) . "<br>\n";
time() should return the current unix timestamp.
If you are working with dates and times across time zones you should work with everything in GMT to avoid time zone issues. If you need to display a date and time at some point that is the place to do any time zone conversion that may be necessary.
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
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.
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;