Use date_format in model or controller? - php

I have retrieving a date and time from the database in this format:
2017-11-25 21:08:48
What I had done before using MVC was:
$date = date_create($row['article_date']);
$article_date = date_format($date, "d F Y - h:ia");
echo $article_date;
I am not sure how to do this using MVC.
My model:
public function getPosts() {
$this->db->query("SELECT `id`, `title`, `article`, `article_date`, `slug` FROM `news`");
$results = $this->db->resultSet();
return $results;
}
The controller:
public function index() {
$posts = $this->postModel->getPosts();
$data = [
'posts' => $posts
];
$this->view('posts/index', $data);
}
Then in the view I would have:
<?php foreach ($data['posts'] as $post){ ?>
// some html here
<?php echo $post->article_date; ?>
I can't just use date_format on the $post->article_date without first using date_create. But I just am not sure where I would use date_create i.e.: would you do that in the model or controller before passing to the view?

Ideally you'd do it in neither, and instead do it in the view:
<?php foreach($data['posts'] as $post){ ?>
// Some HTML here
<?php
$date = date_create($post->article_date);
$article_date = date_format($date, "d F Y - h:ia");
echo $article_date;
} // Remember to close the foreach!
?>
However, note that you don't need to mess around with date_create() at all, and can simply use date() in combination with strtotime() instead:
echo date('d F Y - h:ia', strtotime($post->article_date));
Hope this helps! :)

Related

PHP Format date yyyy-mm-ddThh:ii:ss to Y-m-d h:i:s [duplicate]

This question already has answers here:
Convert a date format in PHP [duplicate]
(18 answers)
Closed 5 years ago.
i need to convert a date with this format (2017-06-14T08:22:29.296-03:00) to Y-m-d H:i:s. I take that date from an xml response from a soap service, And i need to check if the expiration date is less than the actual date.
I have this and works OK on localhost, but when is uploaded to other server, i have validation problems:
if($wsaa->get_expiration() < date("Y-m-d h:m:i")) {
if ($wsaa->generar_TA()) {
echo '<br>Nuevo Ticket de Acceso Generado';
} else {
echo '<br>No se pudo obtener ticket de acceso';
}
} else {
echo '<br>TA expira:' . $wsaa->get_expiration();
}
$wsaa->get_expiration() return 2017-06-14T08:22:29.296-03:00
I tried to format the date but return with a few minutes of diff.
You can use date function for format and use strtotime to convert current date to timestamp that date function needed:
$datetime = '2017-06-14T08:22:29.296-03:00';
$format_date = date('Y-m-d H:i:s', strtotime($datetime));
An alternative solution in OOP using Carbon from http://carbon.nesbot.com. If you run my example, you might notice that solution1() is an hour behind. That's the reason why I recommend Carbon is that it plays really well with time-zones.
First run "composer require nesbot/carbon";
<?php
require 'vendor/autoload.php';
use Carbon\Carbon;
class FormatDate
{
protected $dateTime;
protected $newFormat;
public function __construct($dateTime, $newFormat)
{
$this->dateTime = $dateTime;
$this->newFormat = $newFormat;
}
// Solution 1
public function solution1()
{
$format_date = date($this->newFormat, strtotime($this->dateTime));
return $format_date;
}
// Solution 2
public function solution2()
{
$date = Carbon::parse($this->dateTime)->format($this->newFormat);
return $date;
}
}
$datetime = '2017-06-14T08:22:29.296-03:00';
$newFormat = 'Y-m-d H:i:s';
// Solution 1
echo (new FormatDate($datetime, $newFormat))->solution1();
echo '----------------------------';
// Solution 2
echo (new FormatDate($datetime, $newFormat))->solution2();

Time calculation in laravel taking input from user

i want to calculate the time difference and insert it into database...my model name is "booking" and the start time and end time will be taken input from users..and total_duration will be calculated from these two and will be inserted into database...i use these codes...but won't working.this is my controller.
<?php
/*namespace App\booking;*/
use Carbon\Carbon;
namespace App\Http\Controllers;
use App\booking;
use Illuminate\Http\Request;
use Illuminate\Database\Eloquent\Model;
class RoombookController extends Controller
{
public function showreport(Request $request)
{
/* dd($request->all());
*/ $time= Carbon.now();
$booking = new booking;
$booking->bookdate = $request->input('bookdate');
$booking->roomname = $request->input('roomname');
//echo $datefrom;
$booking->starttime =$startTime= $request->input('starttime');
$booking->endtime = $finishTime=$request->input('endtime');
$booking->purpose = $request->input('Purpose');
//echo $dateto;
$time->sTime = Carbon::parse($startTime);
$time->fTime = Carbon::parse($finishTime);
$time->total_time = $fTime->diffForHumans($sTime);
$booking->total_duration = $time->total_time;
$booking->save();
}
}
Using Carbon for calculation execution time is not very good idea. Just use plain old microtime():
$start = microtime(true);
.... // Do something here.
$end = microtime(true);
$time = $end - $start;
I think you should first convert it into seconds
$totalDuration = $finishTime->diffInSeconds($startTime);
and then desirable format
gmdate('H:i:s', $totalDuration);
or try this if this work for you
$finishTime->diff($startTime)->format('%H:%i:%s');

Send controller data into form field in Yii

UPDATED THE SOLUTION::: IT IS WORKING NOW
I have created a controller with join query. Now I want to include controller to actionCreate function and show data into text filed in form.
Controller
public function actionCreate()
{
$model=new Grndetail;
if (isset($_POST['Grndetail'])) {
$model->attributes=$_POST['Grndetail'];
if ($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$grndata = $this->GrnData1();
$model->im_grnnumber = $grndata['im_grnnumber'];
$this->render('create',array('model'=>$model, 'grndata'=>$grndata,));
}
public function GrnData1()
{
$sql = Yii::app()->db->createCommand()
->select('t.im_grnnumber, t.im_purordnum, r.pp_purordnum, r.cm_code, r.pp_quantity, r.pp_unit, r.pp_unitqty, r.pp_purchasrate, p.cm_description, p.cm_code')
->from('im_grnheader t')
->join('pp_purchaseorddt r', 't.im_purordnum = r.pp_purordnum')
->join('cm_productmaster p', 'p.cm_code = r.cm_code')
//->where('id=:id', array(':id'=>$id))
->order('im_grnnumber DESC')
->queryRow();
return $sql;
}
form filed
<?php echo $form->textField($model,'im_grnnumber'); ?>
Is anything I am missing. How can I view the data as value in form when I am creating something.
Thanks in advanced.
UPDATED THE SOLUTION::: IT IS WORKING NOW
You should change your program as
public function GrnData1(){
$sql = Yii::app()->db->createCommand()->setFetchMode(PDO::FETCH_OBJ) // change it
->select('t.im_grnnumber, t.im_purordnum, r.pp_purordnum, r.cm_code, r.pp_quantity, r.pp_unit, r.pp_unitqty, r.pp_purchasrate, p.cm_description, p.cm_code')
->from('im_grnheader t')
->join('pp_purchaseorddt r', 't.im_purordnum = r.pp_purordnum')
->join('cm_productmaster p', 'p.cm_code = r.cm_code')
->order('im_grnnumber DESC')
->queryRow();
Return $sql; // write here return statement
}
Now you can access your data like this
echo $form->textField($model,'im_grnnumber', array('value'=>$grndata->im_grnnumber));
Hope, It will help you.
Thanks
Var $grndata is an array, not a model. So the correct way to call its values should be this:
<?php echo $form->textField($model,'im_grnnumber', array('value'=>$grndata['im_grnnumber']) ); ?>
Or something like that, I'm not sure of the format of the array returned by queryRow(). Maybe print_r($grndata) to see the style of the array.
change actionGrnData1() to GrnData1()
You should complete your textField like this
<?php echo $form->textField($model,'im_grnnumber',
array('value'=>$grndata->im_grnnumber
)); ?>

Is it possible to change the system date for php (only)

Is it possible to change the system date for php (only).
I want this for debugging/testing purpose.
//Test 1 (2010-01-01)
$datetime = new DateTime(); //(2010-01-01)
//Test 2 (2010-02-01)
$datetime = new DateTime(); //(2010-02-01)
I can't really change the real system clock, because other developers are working on the same system (well I could but still).
I'm just hoping this is possible, or that someone knows a nice trick.
When I print the phpinfo(); I see the following line:
Timezone Database internal
Maybe it's changeable to something like "manual" and ad a timezone with +120
Thanks!
This sounds like an encapsulation issue -- why not search for all mentions of date() or time() and replace them with $site->getDisplayedDate(), or something else appropriate to your code?
I feel your pain, but I don't think there's any way to do this. Think about it this way... how would you feel if, in some unrelated code, you called time() and it gave you some date 3 weeks in the future?
You can change only timezone (and ofcourse only couple hours forward / backward; and not whole day forward), but thats not correct solution...
You could create your own DateTime class that extends the default DateTime and hence change the behaviour:
<?php
class CustomDateTimeVariables {
public static $date = 'now';
}
class CustomDateTime extends DateTime {
public function __construct($time = null, DateTimeZone $timezone = null) {
if ($time === null) {
$time = CustomDateTimeVariables::$date;
}
if ($timezone !== null) {
parent::__construct($time, $timezone);
} else {
parent::__construct($time);
}
}
}
CustomDateTimeVariables::$date = '2010-01-01';
$datetime1 = new CustomDateTime();
CustomDateTimeVariables::$date = '2010-01-02';
$datetime2 = new CustomDateTime();
var_dump($datetime1->Format('Y-m-d H:i:s')); //"2010-01-01 00:00:00"
var_dump($datetime2->Format('Y-m-d H:i:s')); //"2010-01-02 00:00:00"
?>
DEMO
This way you can also set the default time very easily (check CustomDateTimeVariables):
<?php
class CustomDateTimeVariables {
public static $date = 'now +120 hours';
}
class CustomDateTime extends DateTime {
public function __construct($time = null, DateTimeZone $timezone = null) {
if ($time === null) {
$time = CustomDateTimeVariables::$date;
}
if ($timezone !== null) {
parent::__construct($time, $timezone);
} else {
parent::__construct($time);
}
}
}
$datetime = new CustomDateTime();
var_dump($datetime->Format('Y-m-d H:i:s')); //"2013-10-29 13:37:39"
?>
..and when it goes live, you can simply change the default back to now.

Managing date formats differences between PHP and MySQL

I'm writing my first PHP app that has to directly deal with dates, and thus to directly deal with the fact that PHP and MySQL have different date formats.
My question is: what's the most elegant way to manage this difference?
I have the following two functions to manage the difference using php:
function mysql_date($php_date) {
return date( 'Y-m-d H:i:s', $php_date );
}
function php_date($mysql_date) {
$val = explode(" ",$mysql_date);
$date = explode("-",$val[0]);
$time = explode(":",$val[1]);
return mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);
}
is there a simpler way to manage this directly within my SQL queries?
Or could you suggest any other more elegant way to manage this?
Since (around) PHP 5.2, PHP has had a built in class/object for dealing with Dates and Times, called DateTime. In a void, it's always better to use a built-in than to wrangle with the messy details yourself.
The DateTime constructor (or the date_create function) accepts a date in any format understood by strToTime. All you need to know about strToTime is it's magic voodoo that will correctly recognize a date in almost any string format. When I first encountered strToTime I had the same internal reaction you're having now ("that's bullshit/seems unreliable"). It's not. It Just Works in a way that your own fragile understanding of dates never will (and if you think you understand dates, you don't. Trust Me.)
So, pull the information from MySQL as a Date/Time string, and immediately create a PHP date Object. Use the date_format method (with some handy constants) when/if you need the date again as a string.
You can replace php_date with strtotime.
$php = strtotime($mysql);
The MySQL equivalent would be UNIX_TIMESTAMP.
Though, if you want to handle formatting in SQL, try MySQL's DATE_FORMAT.
Store everything in the database in a datetime field in UTC. For PHP manipulation, use the PEAR Date library. I'm not a big PEAR user, but this library is fantastic and will handle all of annoying date conversion issues that you should not be spending your time worrying about.
I would recommend you keep everything in mysql format until you need to display it to the user, then use strtotime() to get a unix timestamp and date() to format it.
If you throw in some Hungarian Notation it's even harder to go wrong:
$ymdDateAdded = date('Y-m-d');
$timeDateAdded = strtotime($ymdDateAdded);
$userDateadded = date('j F Y', $timeDateAdded);
I think it would be a better ideea to store unix timestamps in the DB field. When you need to display dates to human language, you can always use php's date() function. For everything else, just use the numeric timestamp.
You could make a small date object which simply converts the date as you need it
$Date_p = new MagicDate($php_date);
$Date_m = new MagicDate($mysql_date);
The $Date_p and $Date_m are just showing that you can seed the object anyway you need to. When you want a mysql date you would have code like. Realistically it would be something pretty generic like $Date.
$query = "UPDATE SET Date='".$Date_p->toMysql()."' "...
and vice versa when you need the opposite. You can use the functions you've already created. Just add a "sniffer" in the construct method like:
public function __construct($date)
{
$phpdate = strtotime($date);
if($phpdate)
{
$this->phpdate = $phpdate;
$this->mysqldate = $this->mysql_date($phpdate);
}
else
{
$this->phpdate = $this->php_date($phpdate);
$this->mysqldate = $phpdate;
}
}
Throw some error handling in to catch the things that go bad. Add the getter for the two dates. And it's a set it and forget it situation. Just pull the right date out when you need it.
There could be some optimizations, but this is to just show you how it could work.
It is best way to save time and date as unix timestamp rather than other formats.
I have created a class to handle date and time in php. Its easy to use and very very useful
<?php
define("NEW_LINE", "</BR>");
class scTimestamp
{
private $timestamp;
private $year;
private $month;
private $day;
private $hour;
private $minute;
private $second;
public function __construct()
{
register_shutdown_function(array($this,'__destruct'));
$this->setTimestamp($_SERVER['REQUEST_TIME']);
}
public function __destruct()
{
unset($this->timestamp);
unset($this->year);
unset($this->month);
unset($this->day);
unset($this->hour);
unset($this->minute);
unset($this->second);
}
private function rebuildTimestampFromDate()
{
$this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year);
}
private function rebuildDateFromTimestamp()
{
$this->day=date('j',$this->timestamp);
$this->month=date('n',$this->timestamp);
$this->year=date('Y',$this->timestamp);
$this->hour=date('g',$this->timestamp);
$this->minute=date('G',$this->timestamp);
$this->second=date('s',$this->timestamp);
}
public function setTimestamp($tempTimestamp)
{
$this->timestamp=$tempTimestamp;
$this->rebuildDateFromTimestamp();
}
public function getTimestamp()
{
return $this->timestamp;
}
public function setYear($tempYear)
{
$this->year = $tempYear;
$this->rebuildTimestampFromDate();
}
public function getYear()
{
return $this->year;
}
public function setMonth($tempMonth)
{
$this->month = $tempMonth;
$this->rebuildTimestampFromDate();
}
public function getMonth()
{
return $this->month;
}
public function setDay($tempDay)
{
$this->day=$tempDay;
$this->rebuildTimestampFromDate();
}
public function getDay()
{
return $this->day;
}
public function setHour($tempHour)
{
$this->hour = $tempHour;
$this->rebuildTimestampFromDate();
}
public function getHour()
{
return $this->hour;
}
public function setMinute($tempMinute)
{
$this->minute = $tempMinute;
$this->rebuildTimestampFromDate();
}
public function getMinute()
{
return $this->minute;
}
public function setSecond($tempSecond)
{
$this->second = $tempSecond;
$this->rebuildTimestampFromDate();
}
public function getSecond()
{
return $this->second;
}
public function getDateDifferenceFromNow()
{
return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']);
}
public function getDateDifferenceFrom($fromDate)
{
$return="";
$sec=" Second";
$min=" Minute";
$hrs=" Hour";
$before=" Before";
$difference=$fromDate-$this->getTimestamp();
if($difference<0)
$return.="In the Future";
else if($difference<60)
{
if($difference>1)
$sec.="s";
$return.= $difference.$sec.$before;
}
else if($difference<3600)
{
$difference=intval($difference/60);
if($difference>1)
$min.="s";
$return.=$difference.$min.$before;
}
else if($difference<86400)
{
$difference=intval($difference/3600);
if($difference>1)
$hrs.="s";
$return= $difference.$hrs.$before;
}
else if($difference<604800)
{
$return.= date("l g:i a",$this->getTimestamp());
}
else if($difference<28512000)
{
$return.= date("F j",$this->getTimestamp());
}
else
{
$return.= date("F j, Y, g:i a",$this->getTimestamp());
}
return $return;
}
public function getDateAsString()
{
return date("F j, Y",$this->getTimestamp());
}
public function getDateTimeAsString()
{
return date("F j, Y, g:i a",$this->getTimestamp());
}
public function __toString()
{
$return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^";
$return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE;
$return.= NEW_LINE."## Timestamp: ".$this->getTimestamp()." ##".NEW_LINE;
$return.= NEW_LINE."## Date: ".$this->getDateTimeAsString()." ##".NEW_LINE;
$return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE;
return $return;
}
}
?>
once it is included it can be used as follow
include_once("scTimestamp.php");
$test=new scTimestamp();
echo $test->getDateAsString();
$test->setTimestamp(1210203200);
echo $test->getDateDifferenceFromNow();
echo $test;
$test->setTimestamp(121020320022);
echo $test->getYear();
echo $test;
And the result would like this.
June 26, 2015May 7, 2008, 11:33 pm
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
## Timestamp: 1210203200 ##
## Date: May 7, 2008, 11:33 pm ##
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5804
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
## Timestamp: 121020320022 ##
## Date: December 25, 5804, 3:33 am ##
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This class can be used as per needs

Categories