I have to create an array with date/time of each row.
I am using the following code. "TIME_STAMP" is the field which contains MySQL Timestamp (CURRENT_TIMESTAMP default).
while ( $row = mysql_fetch_array($result) )
{
$timestamp = strtotime($row["TIME_STAMP"]);
$x[] = sprintf("%s, %s", date ('j/n', $timestamp), date('H:i', $timestamp));
}
If i make a SELECT * from mysql client all is ok: TIME STAMP is correct:
2013-06-04 17:11:43
but when I pass this array to JpGraph (to make horizontal axis) all the records are displayed with
1/1 01:00
The code for the graph:
$graph = new Graph("1024", "800");
$graph->SetScale( 'textlin');
$graph->img-> SetMargin(60,40,40,110);
$graph->xaxis->SetTickLabels( $x );
$graph->xgrid->Show(true);
Any hint?
My guess here is that the value you're dealing with is a string, rather than an actual DateTime object. You might want to create a new DateTime object with that string before passing it along to the next step.
http://www.php.net/manual/en/function.date-create.php
You have:
$graph->SetScale( 'textlin');
it should be:
$graph->SetScale( 'datlin');
Fixed
My select query didn't include "TIME_STAMP" field; the graph was added later, but query wasn't updated with new attributes for JpGraph.
Thanks anyone for the help.
Related
I am trying to format a time cell using PHPSpreadsheet but it seems to be including the date as well when looking at the formula bar. There also seems to be some inconsistency when converting from a string, datetime object or unix timestamp.
<?php
include '../vendor/autoload.php';
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use \PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$times = [
'16:00:00',
new \DateTime('16:00:00'),
\strtotime('16:00:00'),
'2020-04-04 16:00:00',
new \DateTime('2020-02-04 16:00:00'),
\strtotime('2020-02-04 16:00:00'),
];
$format = \PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME1;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
foreach ($times as $i => $time) {
$sheet->setCellValue('A' . ($i+1), \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($time));
$sheet->getStyle('A' . ($i+1))->getNumberFormat()->setFormatCode($format);
}
$writer = new Xlsx($spreadsheet);
$writer->save('test.xlsx');
From \PHPOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_TIME1: const FORMAT_DATE_TIME1 = 'h:mm AM/PM';
Is this a bug or intended functionality? Considering as const FORMAT_DATE_DATETIME = 'd/m/yy h:mm'; does include some date parameters I think there's something wrong happening.
Here's some screenshots of what happens:
But if we type in "5:00 AM" into a cell, the formula bar does not include the date:
Here is the screen that pops up from Right Click > "Format Cell":
Can someone please tell me if I'm doing something wrong, thankyou.
I figured out how to fix this problem: You need to calculate the Excel representation of the timestamp and then get only the numbers after the decimal place.
<?php
$timestamp = new \DateTime('16:00:00');
$excelTimestamp = \PhpOffice\PhpSpreadsheet\Shared\Date::PHPToExcel($timestamp);
$excelDate = floor($excelTimestamp);
$time = $excelTimestamp - $excelDate;
From the documentation:
In Excel, dates and Times are stored as numeric values counting the number of days elapsed since 1900-01-01. For example, the date '2008-12-31' is represented as 39813. You can verify this in Microsoft Office Excel by entering that date in a cell and afterwards changing the number format to 'General' so the true numeric value is revealed. Likewise, '3:15 AM' is represented as 0.135417.
I hope this helps anybody else stuck with this problem.
You must set the right number format see for more information the official sample documentation.
The number format that you set is 'h:mm AM/PM' means that there is no date included only the time.
When you change to 5 PM you overwrite the content and the number format will used.
If you will have a date you should try to set 'd/m/yy h:mm AM/PM'.
I have a table transaction, inside there is column order_on_sale with default value is 0. Then i also have a table config, inside there is column name with two value that is sale_start_date and sale_finish_date. And there are also time columns with values 2018-05-1 18:00 and 2018-05-31 18:00 (YYYY-MM-DD HH: mm).
name and time columns contained in the config table are interconnected,
sale_start_date = 2018-05-1 18:00
sale_finish_date = 2018-05-31 18:00
then when someone orders on sale_start_date and sale_finish_date, the order_on_sale column contained in transaction table will change its value to 1
how do i get the current current time (YYYY-MM-DD HH: mm) to make the change?
$transaksi = new Transaction;
$order_on_sale = 0;
if (Config::get('sale_start_date') && Config::get('sale_finish_date')) {
$order_on_sale = 1;
}
$transaksi->order_on_sale = $order_on_sale;
$transaksi->save();
Below is my code, but I am confused how to get the current date and time if I write such code
thanks for the answers you provide
A bit late answer for questioner but maybe can help someone:
$date = Carbon::now();
$formatedDate = $date->format('Y-m-d H:i:s');
echo($formatedDate);
use the Carbon Library which comes by default with laravel
$date = Carbon::now();// will get you the current date, time
dd($date->format("Y-M-D H:m")); //this will dump the date time in the desired format
Maybe with:
use Carbon\Carbon;
$Now = Carbon::now(new \DateTimeZone('My/TimeZoneifRequired'))->toDateTimeString();
So have you tried using Carbon Class ? as far as i know Laravel 4 supports it.
you can get your current date by doing
$now = Carbon::now()->toDateTimeString();
This will retrieve the current date in the following format YYYY-MM-DD HH:mm:ss (as default)
if you want to get the current date in your mentioned format YYYY-MM-DD HH:mm
by wrapping around Carbon and adding some php functionality you can get so :
$currentTime = Carbon::now()->toTimeString();
$now = Carbon::now()->toDateString() .' '. substr($currentTime, 0, strrpos( $currentTime, ':') ) ;
For further explanation go for the docs : https://carbon.nesbot.com/docs/
simply you can use the below code on the view page.
<p>{{ date('Y-m-d') }}</p>
note: HTML <p> tag is optional.
with hours and minutes
<p>{{ date('Y-m-d H:m') }}</p>
I am working with the DateTime object and have this problem to obtain the activity of a specific day.
In the controller I do the following query:
$date = new \DateTime('today');
$activity = $em->getRepository('MyBundle:myEntity')->findOneBy(array(
'activity_date' => $date
));
Result for this query is null, but when I define the parameter date in this way:
$date = new \DateTime('Wednesday, January 14, 2015');
I get the activity that matches this date. Why doesn't today work?
I believe that commenter #prodigitalson is right. When you say today that is in fact now which is formatted with YYYY-MM-DD HH:MM:SS.
Now, if your DBMS column is of type date, DBMS will first normalize two values and only then proceed with comparing.
If your incoming parameter has a value of 2014-01-14 16:47:20, comparing it to DBMS value of 2014-01-14 00:00:00 will no match the record.
Try the following:
$date = new \DateTime(); // no need for explicit `today`
$date->setTime(0,0,0); // reset hours, minutes and seconds to 0
$activity = $em->getRepository('MyBundle:myEntity')->findOneBy(array(
'activity_date' => $date
));
Will this work?
I have a string of a date:
25/08/2012
And here I'm trying to convert it to a DateTime object in order to save it to the MySQL database. My backend schema has a DateOfPrint date column ready to receive this data.
Here's what I've tried:
$eventDate = DateTime::createFromFormat('d/m/y', $fecha->innertext);
echo $eventDate;
The echo statement doesn't show anything on the screen, and when trying to save it to the database, nothing is saved in that column.
Any suggestions?
Your $eventDate contains a boolean(false) which is printed as empty string.
You need to use an upper-case Y.
Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003
y A two digit representation of a year Examples: 99 or 03
And you have to call DateTime::format();
e.g.
<?php
$fecha = new StdClass;
$fecha->innertext = '25/08/2012';
$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
if ( false===$eventDate ) {
die('invalid date format');
}
echo $eventDate->format('Y-m-d');
prints
2012-08-25
You need to format it for a MySQL column before you can insert it:
// Need upper case Y here, thanks to VolkerK for pointing that out
$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
$eventDate = $eventDate->format( 'Y-m-d'); // I think this is the correct format
Then you can use $eventDate to save the date to the database.
$eventDate is an object, not a string. You will need to access the properties of the element in your code to be able to correctly insert it's value into a table or echo it out. On that note, you could use a var_dump($eventDate); which should show you all there is to know about the object.
You can reference the PHP docsm on the DateTime class to get the available properties and see which one best fits your needs.
$eventDate = DateTime::createFromFormat('d/m/Y', $fecha->innertext);
echo $eventDate->format('Y-m-d');
short answer
$st_time = date('Y-m-d H:i',$yourdate);
if you want only day month and year use this
$st_time = date('Y-m-d',$yourdate);
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;