date_format() expects parameter 1 to be DateTimeInterface, boolean given - php

I made CRUD laravel by including the date on the form, but I got an error in the controller, and the contents of the controller:
public function update(Request $request, $id)
{
$suratmasuk= \App\SuratMasuk::find($id);
$suratmasuk->no_surat=$request->get('no_surat');
$suratmasuk->no_agenda=$request->get('no_agenda');
$tgl_surat=date_create($request->get('tgl_surat'));``
$format = date_format($tgl_surat,"Y-m-d");
$suratmasuk->tgl_surat = strtotime($format);
$tgl_terima=date_create($request->get('tgl_terima'));
$format = date_format($tgl_terima,"Y-m-d");
$suratmasuk->tgl_terima = strtotime($format);
$suratmasuk->sumber_surat=$request->get('sumber_surat');
$suratmasuk->perihal=$request->get('perihal');
$suratmasuk->keterangan=$request->get('keterangan');
$suratmasuk->save();
return redirect('surat-masuk');
}

$stamp= time();
$daystotal = date("Y-m-d h:i:s",$stamp);
$postdate = date_create(date_create_from_format('Y-m-d',$daystotal))
echo date_format($daystotal,"j M,y H:i");
Output : "j M, y H:i

Related

ErrorException strtotime() expects parameter 1 to be string, array given

Can anyone help me? this is my controller, when i try to store 'purchase' data it show this message strtotime() expects parameter 1 to be string, array given
The error was on the $purchase->date = date('Y-m-d', strtotime($request->date)); and $purchaseDetail->date = date('Y-m-d', strtotime($request->date));
public function store(Request $request){
if($request->category_id == null){
return redirect()->back()->with('error', 'Please Purchase The Product');
} else{
// Multipale Data Insert start //
$purchase = new purchase();
$purchase->purchase_no = $request->purchase_no;
$purchase->date = date('Y-m-d', strtotime($request->date));
$purchase->description = $request->description;
$purchase->status = '0';
$purchase->created_by = Auth::user()->id;
DB::transaction(function() use($request,$purchase) {
if($purchase->save()) {
// Purchase Details Insert Start //
$category_id = count($request->category_id);
for ($i=0; $i < $category_id; $i++) {
$purchaseDetail = new purchaseDetail();
$purchaseDetail->date = date('Y-m-d', strtotime($request->date));
$purchaseDetail->purchase_id = $purchase->id;
$purchaseDetail->supplier_id = $request->supplier_id[$i];
$purchaseDetail->category_id = $request->category_id[$i];
$purchaseDetail->product_id = $request->product_id[$i];
$purchaseDetail->buying_qty = $request->buying_qty[$i];
$purchaseDetail->unit_price = $request->unit_price[$i];
$purchaseDetail->buying_price = $request->buying_price[$i];
$purchaseDetail->discount_amount = $request->discount_amount[$i];
$purchaseDetail->ppn = $request->ppn[$i];
$purchaseDetail->status = '0';
$purchaseDetail->save();
}
}
});
}
// Redirect
return redirect()->route('purchase.view')->with('success', 'Purchase Added Successfully');
}
Hello, i try to change $purchase->date = date('Y-m-d', strtotime($request->date)); into $purchase->date = $request->date;
But the result was TypeError
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in D:\Project Laravel\alc-pos\vendor\laravel\framework\src\Illuminate\Database\Query\Grammars\Grammar.php on line 869
As for my opnion you must not format your date when saving to database.
Instead you can format it when outputit from database into your blade templates.
Anyway make a check on $request->date, seems to be an array.
You can format your date using Laravel accessor in your model like this (example):
public function getFormattedStartDateAttribute()
{
return $this->start_date->format('d-m-Y');
}
and then call it in your blade template like this (example):
<input type="text" name="start_date" class="form-control" value="{{$trip->formatted_start_date}}">
More info about Laravel Mutators & Accessors : Laravel Docs
Also you can do another thing. On your schema::create make:
$table->date('date_name_column');
and then just save it like follow:
$purchaseDetail->date = $request->input('date');
This way the date in your database will be save as follow : YYYY-MM-DD
Hope it helps!

Problem in checking when date and time has elapse using timezone

Am trying to create a date and time function to check if a given dateTime and timezone passed but my function is always returning true even when i put a future date.
I have below example class
<?php
class JobTimer{
public function __construct() {
}
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = \DateTime::createFromFormat('M d, Y H:i:s', $startOn, new \DateTimeZone($timezone));
return ($nowTime >= $startTime ? true : false);
}
}
?>
Usage
Everything is returning true, my expectation is to return false if current time based on timezone has not yet elapse or return true when time has elapse or time is now
<?php
$job = new JobTimer();
//if($job->isDateTime("2019-05-02 12:00AM", "Asia/Kuala_Lumpur")){
//if($job->isDateTime("2021-05-02 12:00AM", "Asia/Kuala_Lumpur")){
if($job->isDateTime("2020-05-02 12:00AM", "Asia/Kuala_Lumpur")){
echo "YES";
}else{
echo "NO";
}
?>
In your JobTimer class $startTime is false because your format for DateTime::createFromFormat() does not match the format of the date you are passing in as a parameter and causing it to fail.
M d, Y H:i:s matches May 02, 2020 12:00:00 which is not what you are passing to that class.
You should be using:
$startTime = \DateTime::createFromFormat('Y-m-d H:iA', $startOn, new \DateTimeZone($timezone));
Working code:
class JobTimer{
public function __construct() {
}
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = \DateTime::createFromFormat('Y-m-d H:iA', $startOn, new \DateTimeZone($timezone));
return $nowTime >= $startTime;
}
}
$job = new JobTimer();
if($job->isDateTime("2020-05-02 12:00AM", "Asia/Kuala_Lumpur")){
echo "YES";
}else{
echo "NO";
}
Output:
NO
Demo
Change your function to this:
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = new \DateTime($startOn, new \DateTimeZone($timezone));
return ($nowTime >= $startTime ? true : false);
}
Your argument passed to createFromFormat is wrong, and therefore not creating a DateTime correctly. You can just pass your $startOn and a DateTimeZone to create a instance of DateTime

Get current date records from table with different time zone

This question is related to my previews one: How to change time zome in different tables in Laravel
After I mark the answer, discover a problem:
When user load the page it need to gives him records for the current day.
For example from 00:00:00 to now.
The problem is that the controller is asking the DB to give records from 00:00:00 in UTC, after this my model(in the link above) parsing it to LOCAL time.
This local time is Europe/Sofia (+3 hours), causing to miss 3 records from today starting with 03:00:00.
Any idea how to fix it?
The controller:
function getdata_chart(Request $request)
{
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$students = MeasCanal::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Кота\') as iazovir')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Температура\') as temperatura350')
->where(function ($query) {
$query->where('fullname', 'like', "Язовир.Данни.Кота")
->orWhere('fullname', 'like', "ГСК_11_350.Данни.Температура");
})
->groupBy('recordtime')
->orderBy('recordtime')
->get();
return response()->json($students);
}
return response()->json($students);
}
The model:
class MeasCanal extends Model
{
protected $connection = 'MeasCanal';
protected $table = 'meas_kanal';
protected $fillable = ['fullname','formattedvalue','recordtime','qualitydesc','statedesc','id'];
/**
* Get the user's recordtime.
*
* #param string $value
* #return string
*/
public function getRecordtimeAttribute($value)
{
return Carbon::parse($value)->timezone('Europe/Sofia')->toDateTimeString();
}
}
You have to map the user input date from the DB timezone to the user timezone by calling the carbon method and array map function. and call the query as it is.
function getdata_chart(Request $request) {
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$dbTimeZone = 'Asia/Kolkata'; // update with your db timezone
$userTimeZone = 'Europe/Sofia';
$dateScope = array_map(function($date) use ($dbTimeZone, $userTimeZone) {
return Carbon::createFromFormat('d-m-Y H:i:s', $date, $dbTimeZone)->setTimezone($userTimeZone);
}, $dateScope);
$students = MeasCanal::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Кота\') as iazovir')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Температура\') as temperatura350')
->where(function ($query) {
$query->where('fullname', 'like', "Язовир.Данни.Кота")
->orWhere('fullname', 'like', "ГСК_11_350.Данни.Температура");
})
->groupBy('recordtime')
->orderBy('recordtime')
->get();
return response()->json($students);
}
return response()->json($students);
}
Note that:- add the following line to the controller if you are not using carbon til yet.
use Carbon\Carbon;
The problem was that date separator was different on each fuction causing Unexpected data found.. After edit him the answer of Sachin Kumar did the job. Thanks for that.
Just discover the problem with similar long way solution:
$start_date0 = date('d-m-Y 00:00:00');
$end_date0 = date('d-m-Y 23:59:59');
$start_date = Carbon::createFromFormat('d-m-Y H:i:s', $start_date0, 'Europe/Sofia')->setTimezone('UTC');
$end_date = Carbon::createFromFormat('d-m-Y H:i:s', $end_date0, 'Europe/Sofia')->setTimezone('UTC');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$start_date0 = $request->start_date;
$end_date0 = $request->end_date;
$start_date = Carbon::createFromFormat('d/m/Y H:i:s', $start_date0, 'Europe/Sofia')->setTimezone('UTC');
$end_date = Carbon::createFromFormat('d/m/Y H:i:s', $end_date0, 'Europe/Sofia')->setTimezone('UTC');
$dateScope = array($start_date, $end_date);
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};

error datetime on PHP

hello i need help please. mi code is error sorry for my bad englihs.
error : Fatal error: Call to a member function format() on boolean in C:\xampp\htdocs\aplicacion\application\views\guest\container.php on line 11
My container.php
My intention is to get the date of creation of the blog. Be added to the url of my website. And also the name of the post
<?php
foreach ($consulta->result() as $fila) {
?>
<div class="post-preview">
<?php
$date = DateTime::createFromFormat('YYYY-MM-DD', $fila->fecha);
$year = $date->format('Y',$date);
$name = str_replace('','_', $fila->post);
?>
<a href="<?php echo base_url()?>article/post/<?php echo $year ?>/<?php echo $name ?>">
article.php - controller
class article extends CI_Controller
{
public function post($year , $name)
{
// $fila = $this->post->getPostByName($id);
$fila = $this->post->getPostByYearAndName($year , $name);
if($fila == null){
echo "ERROR";
return;
}
$data = array('titulo' => $fila->post);
$this->load->view("guest/head" , $data);
$data = array('app' => 'blog');
$this->load->view("guest/nav" , $data);
$data = array(
'post' => $fila->post,
'descripcion' => $fila->descripcion,
'img' =>$fila->img);
$this->load->view("guest/header" , $data);
$data = array('contenido' => $fila->contenido);
$this->load->view("/guest/post" , $data);
$this->load->view("guest/footer");
}
post.php - MODEL
public function getPostByYearAndName($year = '', $name = '')
{
$result = $this->db->query("SELECT * FROM post WHERE year(fecha) = '$year' AND post LIKE '$name'");
return $result->row();
}
Your code works:
$date = DateTime::createFromFormat('y-m-d', '17-03-12');
echo $date->format('Y');
->
2017
if $date is false it means that your input $fila->fecha is not at the format YY-MM-DD.
If for example, your date is at the format YYYY-MM-DD you will have to use 'Y-m-d' instead.
Update:
Just to illustrate, if the input is a date but not at the specified format, for example:
$date = DateTime::createFromFormat('y-m-d', '2017-03-12');
echo $date->format('Y');
It reproduces OPs bug:
PHP Fatal error: Uncaught Error: Call to a member function format() on boolean in ~/tmp/date.php:5
So either $fila->fecha is empty, not a date or not at the format YY-MM-DD

php add method incorrectly working

I'm in the process of learning PHP and i'm having some trouble. My function is returning the "milestones" with the same date they were plugged in with. I believe I am using the add() method incorrectly. Thankyou.
PHPplayground: http://www.tehplayground.com/#cARB1wjth
$milestones = null;
$milestones = createMilestone($milestones, true, 10, "15-1-1", "birthday" );
var_dump( $milestones );
function createMilestone($milestones, $forward, $days, $startDate, $milestoneName ){
if ( is_string($startDate)){
$date = DateTime::createFromFormat("Y-m-d", $startDate );
}else if(is_array($startDate) ){
$date = $startDate["date"];
}else{
$date = $startDate;
};
$daysInterval = DateInterval::createFromDateString($days);
if ($forward){
$date->add($daysInterval);
}else{
$date->sub($daysInterval);
}
$milestones[$milestoneName]['date'] = $date;
return $milestones;
}
You need to use :
$daysInterval = DateInterval::createFromDateString($days . ' days');
See the doc here for DateInterval and that page for the diverse date formatting (called relative format) you can use.
And BTW, if you give a DateTime like "15-1-1", the correct format is not "Y-m-d" but "y-m-d" (lowercase 'y')

Categories