I try to check if today is the 3 days after the registration day or not, so i compare today date with the registration date plus 3 days. But i think my code is not working, this is my code:
$get_tanggal_permohonan = DB::table('data_pemohon')->select('tanggal_permohonan')->where('noper', $noper)->first();
$tanggal_permohonan = $get_tanggal_permohonan->tanggal_permohonan;
$Dday = \Carbon\Carbon::parse($tanggal_permohonan);
$today = \Carbon\Carbon::now()->toDateString();
$today = \Carbon\Carbon::parse($date);
if($today < $Dday->subDays(3)){
echo "not the time to come";
}else{
echo "time to come"
}
I have no idea to solve this error, help me please. Thank you.
You can use DiffInDays()
if( $Dday->diffInDays($today) > 3){
echo "not the time to come";
}else{
echo "time to come"
}
You can use the isSameDay() method and the Laravel today() helper function:
$get_tanggal_permohonan = DB::table('data_pemohon')->select('tanggal_permohonan')->where('noper', $noper)->first();
$tanggal_permohonan = $get_tanggal_permohonan->tanggal_permohonan;
$Dday = \Carbon\Carbon::parse($tanggal_permohonan);
if ($Dday->addDays(3)->isSameDay(today())) {
echo "not the time to come";
} else {
echo "time to come";
}
Question already anwsered here How to compare two Carbon Timestamps?
if (Carbon::parse($date)->gt(Carbon::now()))
for more http://carbon.nesbot.com/docs/#api-comparison
Related
I am using laravel framework to develop api's , i have one column inside table with timestamp,i am fetching that value and i want to show that value to the 3 Years 2 Month or if it's been in days it should show 10days, i have tried by using carbon package to convert as per my requirement but i can't able to figure out can you please help me to achieve this one.
Ex1:-
$date = 2022-09-15 00:00:00;
//my expectation is **8days**
Ex2:-
$date = 2021-08-23 00:00:00;
//my expectation is 1 year 1 month
Here is the example you can do like this
$Born = Carbon\Carbon::create(1986, 1,3);
$Age = $Born->diff(Carbon\Carbon::now())->format('%y Year, %m Months and
%d Days');
echo $Age;
Here is your date example is working and it's result
$date1 = \Carbon\Carbon::create("2022-09-15 00:00:00");
$date2 = \Carbon\Carbon::create("2021-08-23 00:00:00");
$totalYearMonthDate = $date1->diff($date2)->format('%y Year,
%m Months and %d Days');
Result:-
1 Year, 0 Months and 23 Days
diffForHumans has parts and minimumUnit options that do what you want:
$options = [
'parts' => 2,
'minimumUnit' => 'day',
'skip' => ['week'],
];
echo Carbon::parse('2022-09-15 00:00:00')->diffForHumans($options) . "\n";
echo Carbon::parse('2021-08-23 00:00:00')->diffForHumans($options) . "\n";
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference ". $interval->y . " years, " .
$interval->m." months, ".$interval->d." days ";
Try doing like this
UseCase: Admin assigns tasks to People. Before we assign them we can see their tasks in a gantt chart. According to the task assign date and deadline, conflict days (overlap days) are generated between tasks.
I wrote this function to get overlapping dates between two dates. But now I need to get non overlapping days between two dates, below is the function I wrote.
$tasks = Assign_review_tasks::where('assigned_to', $employee)
->where('is_active', \Constants::$REVIEW_ACTIVE)
->whereNotNull('permit_id')->get();
$obj['task'] = count($tasks);
// count($tasks));
if (count($tasks) > 0) {
if (count($tasks) > 1) {
$start_one = $tasks[count($tasks) - 1]->start_date;
$end_one = $tasks[count($tasks) - 1]->end_date;
$end_two = $tasks[count($tasks) - 2]->end_date;
$start_two = $tasks[count($tasks) - 2]->start_date;
if ($start_one <= $end_two && $end_one >= $start_two) { //If the dates overlap
$obj['day'] = Carbon::parse(min($end_one, $end_two))->diff(Carbon::parse(max($start_two, $start_one)))->days + 1; //return how many days overlap
} else {
$obj['day'] = 0;
}
// $arr[] = $obj;
} else {
$obj['day'] = 0;
}
} else {
$obj['day'] = 0;
}
$arr[] = $obj;
start_date and end_date are taken from database,
I tried modifying it to,
(Carbon::parse((min($end_one, $end_two))->add(Carbon::parse(max($start_two, $start_one))))->days)->diff(Carbon::parse(min($end_one, $end_two))->diff(Carbon::parse(max($start_two, $start_one)))->days + 1);
But it didn't work, in simple terms this is what I want,
Non conflicting days = (end1-start1 + end2-start2)- Current overlapping days
I'm having trouble translate this expression . Could you help me? Thanks in advance
before trying to reimplement complex stuff I recommend you take a look at enhanced-period for Carbon
composer require cmixin/enhanced-period
CarbonPeriod::diff macro method is what I think you're looking for:
use Carbon\CarbonPeriod;
use Cmixin\EnhancedPeriod;
CarbonPeriod::mixin(EnhancedPeriod::class);
$a = CarbonPeriod::create('2018-01-01', '2018-01-31');
$b = CarbonPeriod::create('2018-02-10', '2018-02-20');
$c = CarbonPeriod::create('2018-02-11', '2018-03-31');
$current = CarbonPeriod::create('2018-01-20', '2018-03-15');
foreach ($current->diff($a, $b, $c) as $period) {
foreach ($period as $day) {
echo $day . "\n";
}
}
This will output all the days that are in $current but not in any of the other periods. (E.g. non-conflicting days)
I'm using Laravel 5.7 and carbon 1.x.
I need to build dateLooper which interval is 5 days and follows calender dates.
I need to find the way build looper which add 5 days for startdate.
ex.
$startDate = "2014-01-01";
$interval = "5";
so $endDate = $startDate + 5 ;
so endDates 2014-01-05
2014-01-10
till 2014-01-30, so this is tricky because need to follow calender.
Next 2014-02-04.
I was reading Carbon but did not find any examples
which could have open solution for my problem.
And I realized that L5.7 is still using 1.x carbon.
I have tried to build double for-loop, but did not work
as it stops after reach end of inside loop.
$month ="13" ; // +1;
$day ="29" ; // +1;
for ($i = 1; $i < $month; $i++)
{
echo "Month: ".$i.'<br/>';
for ($i = 1; $i < $day; $i++)
{
echo "Day: ".$i.'<br/>';
}
}
1) So is there way to do with Carbon?
or is there some other library which I could use? Ideas..
Thanks MikroMike.
I found it from How to add CarbonInterval instance in Carbon instance
$carbon = Carbon::now();
$monthLater = clone $carbon;
$monthLater->addDay(15);
dd($carbon, $monthLater);
This has resolved my issue.
I have been trying for a while for saving time in my database in timeformat like 10:00:00.
What I want is simply pick up time from timepicker and save data(time) in timeformat.
Here is what I have done:
I have used timepicker as it gets data in format 10:52 AM.
I have used accessor methods to save time as follows:
public function setRTimeAttribute($value)
{
$this->attributes['r_time'] = date('h:i:A', strtotime($value));
}
My post controller in case needed as follows:
public function postSessionReservation(Request $request,$profile_slug)
{
$restaurant = Restaurant::where('slug_profile', $profile_slug)->select('name','ar_name','slug_profile','id')->firstOrFail();
$this->validate($request,[
'no_of_seats'=>'required',
'r_date'=>'required',
'r_time'=>'required',
'restaurant_id'=>'required',
]);
$data = [
'no_of_seats'=>$request->no_of_seats,
'r_date'=>$request->r_date,
'r_time'=>$request->r_time,
'restaurant_id'=>$request->restaurant_id
];
$minutes = 1;
Session::put('reservation',json_encode($data),$minutes);
return redirect($restaurant->slug_profile.'/complete-reservation');
}
But it saves the time as 12:00:00 each time.
I do not know how 12:00:00 is generated whenever I save the time. I tried a lot but could not figure out.
Hope you guys will help me solve this.
Thanks in advance.
First remove spaces between time "10 : 52 AM" to "10:52 AM" and then change your line to this:
$this->attributes['r_time'] = date('H:i', strtotime( $value ));
This will surely help, I already tested it.
For example you can remove spaces through:
$a = '10 : 52 PM';
$x = preg_replace('/\s*:\s*/', ':', $a);
date("H:i", strtotime($x));
I would like to display a time format like twitter and FB (Posted 3 hours ago, Posted 2 minutes ago and so on...)
I've tried this piece of code without success :
function format_interval($timestamp, $granularity = 2) {
$units = array('1 year|#count years' => 31536000, '1 week|#count weeks' => 604800, '1 day|#count days' => 86400, '1 hour|#count hours' => 3600, '1 min|#count min' => 60, '1 sec|#count sec' => 1);
$output = '';
foreach ($units as $key => $value) {
$key = explode('|', $key);
if ($timestamp >= $value) {
$floor = floor($timestamp / $value);
$output .= ($output ? ' ' : '') . ($floor == 1 ? $key[0] : str_replace('#count', $floor, $key[1]));
$timestamp %= $value;
$granularity--;
}
if ($granularity == 0) {
break;
}
}
I use this function with a callback into another function like : $this->format_interval(); and pass it to my View
My current format date is : 2012-07-26 09:31:pm and already stored in my DB
Any help will be very appreciated!
The Date Helper's timespan() method just does that:
The most common purpose for this function is to show how much time has elapsed from some point in time in the past to now.
Given a timestamp, it will show how much time has elapsed in this format:
1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes
So, in your example, all you need to do is convert your date to a timestamp and do something like this:
$post_date = '13436714242';
$now = time();
// will echo "2 hours ago" (at the time of this post)
echo timespan($post_date, $now) . ' ago';
Try something like this in a my_date_helper.php file (source: Codeigniter Forums):
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if( ! function_exists('relative_time'))
{
function relative_time($datetime)
{
$CI =& get_instance();
$CI->lang->load('date');
if(!is_numeric($datetime))
{
$val = explode(" ",$datetime);
$date = explode("-",$val[0]);
$time = explode(":",$val[1]);
$datetime = mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);
}
$difference = time() - $datetime;
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
$lengths = array("60","60","24","7","4.35","12","10");
if ($difference > 0)
{
$ending = $CI->lang->line('date_ago');
}
else
{
$difference = -$difference;
$ending = $CI->lang->line('date_to_go');
}
for($j = 0; $difference >= $lengths[$j]; $j++)
{
$difference /= $lengths[$j];
}
$difference = round($difference);
if($difference != 1)
{
$period = strtolower($CI->lang->line('date_'.$periods[$j].'s'));
} else {
$period = strtolower($CI->lang->line('date_'.$periods[$j]));
}
return "$difference $period $ending";
}
}
The format is a little different than the one you're using in your database (why do you mark times with pm/am rather than just use 24 hour times and convert for the frontend?). Either way, shouldn't take much work to get it working.
I had a function that solved this like this:
$int_diff = (time() - $int_time);
$str_this_year = date('Y-01-01', $int_time);
$str_weekday = t('time_weekday_'.strtolower(date('l', $int_time)));
$str_month = t('time_month_'.strtolower(date('F', $int_time)));
$arr_time_formats = array( '-90 seconds' => t('time_a_minute_at_most'),
'-45 minutes' => t('time_minutes_ago', ceil($int_diff / (60))),
'-70 minutes' => t('time_an_hour_at_most'),
'-8 hours' => t('time_hours_ago', ceil($int_diff / (60 * 60))),
'today' => t('time_hours_ago', ceil($int_diff / (60 * 60))),
'yesterday' => t('time_yesterday', date('H:i', $int_time)),
'-4 days' => t('time_week_ago', $str_weekday, date('H:i', $int_time)),
$str_this_year => t('time_date', date('j', $int_time), $str_month, date('H:i', $int_time)),
0 => t('time_date_year', date('j', $int_time), $str_month, date('Y', $int_time), date('H:i', $int_time)));
if ($boo_whole)
return $arr_time_formats[0];
foreach(array_keys($arr_time_formats) as $h)
if ($int_time >= strtotime($h))
return $arr_time_formats[$h];
Basicly t() is a function combined with $this->lang->line() and sprintf(). The idea here is to give keys that's runned through strtotime() till you reach the closest time, with 0 being the fallback.
This approach is really good since you can easy adjust the times with a nice overview. I could give more piece of the code, but it feels like doing too much of the work :) Basicly this is just the theory behind how you can do it.
<?php
$this->load->helper('date');
//client created date get from database
$date=$client_list->created_date;
// Declare timestamps
$last = new DateTime($date);
$now = new DateTime( date( 'Y-m-d h:i:s', time() )) ;
// Find difference
$interval = $last->diff($now);
// Store in variable to be used for calculation etc
$years = (int)$interval->format('%Y');
$months = (int)$interval->format('%m');
$days = (int)$interval->format('%d');
$hours = (int)$interval->format('%H');
$minutes = (int)$interval->format('%i');
// $now = date('Y-m-d H:i:s');
if($years > 0)
{
echo $years.' Years '.$months.' Months '.$days.' Days '. $hours.' Hours '.$minutes.' minutes ago.' ;
}
else if($months > 0)
{
echo $months.' Months '.$days.' Days '. $hours.' Hours '.$minutes.' minutes ago.' ;
}
else if($days > 0)
{
echo $days.' Days '.$hours.' Hours '.$minutes.' minutes ago.' ;
}
else if($hours > 0)
{
echo $hours.' Hours '.$minutes.' minutes ago.' ;
}
else
{
echo $minutes.' minutes ago.' ;
}
?>