How to save time in database in timeformat in Laravel 5? - laravel-5

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));

Related

How to get missing dates between 7 latest rows from database?

I want to get 7 latest rows (in order from down to up), for the current week (Sunday to Saturday), for the current logged in user.
To do this, I used this one method:
Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
$strikes = UserStrike::where('user_id', $user)->whereBetween('created_at', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])->latest()->take(7)->get();
$strikes = $strikes->reverse(); //to order the list from DESC to ASC
But the problem with this method is that it doesn't get any missing days.
So if there are data like this for the current week (2020-05-12 is missing):
created_at: 2020-05-10
created_at: 2020-05-11
created_at: 2020-05-13
Then for that one day which is missing, there should be a null in array. Something like this:
$days = ["Sun", "Mon", null, "Wed"];
I'm having hard time to find a way to replace missing day with a null in array.
If anyone here can help me with this problem please leave your comment. Thank you in advance.
You can take data from DB and then create array by iterating on DateTimeInterval(). I don't know Laravel and Carbon well but it could be something like this:
Carbon::setWeekStartsAt(Carbon::SUNDAY);
Carbon::setWeekEndsAt(Carbon::SATURDAY);
$start = Carbon::now()->startOfWeek();
$end = Carbon::now()->endOfWeek();
$strikes = UserStrike::where('user_id', $user)
->whereBetween(
'created_at',
[$start, $end]
)
->latest()
->take(7)
->get();
$strikes = $strikes->reverse();
$timePeriod = new DatePeriod(
$start,
new DateInterval('P1D'),
$end
);
$days = [];
for ($i = 0; $i < count($timePeriod) $i++) {
$days[$i] = null;
foreach ($strikes as $strike) {
if ($strike->created_at->format('Y-m-d') == $timePeriod[$i]->format('Y-m-d') {
$days[$i] = $strike->created_at->format('Y-m-d');
break;
}
}
}

How to calculate experience by using date with current date in laravel?

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

Very strange error with Carbon and Laravel

I'm using Laravel for one of my project. Everything is just fine, but I can't solve a strange error.
I'm sending duration in years from my front end (Vuejs).
If client is on any active plan then plan start should be the current plan end date else set to now().
Add years in start time and set as plan end.
Now when I do this in actual code, I see same start and end date generated according to plan end.
$start = Carbon::parse($client->plan_end) ?: Carbon::now();
$end = $start->addYears($request->planDetails['duration']);
return response([
'start' => $start,
'end' => $end,
]);
This is plan_end timestamp in database -- 2022-05-09 09:15:19
This is response I receive.
{
"start" : "2024-05-09T07:15:19.000000Z",
"end" : "2024-05-09T07:15:19.000000Z"
}
So carbon is mutable which means that when you do ->addYears() it will alter the original start date time. You can use the ->copy() function before adding the years so it would look like this.
$end = $start->copy()->addYears($request->planDetails['duration']);
Using ->copy() is fine, but using CarbonImmutable as default is likely better as it will avoid similar pain to happen again:
$start = CarbonImmutable::parse($client->plan_end) ?: CarbonImmutable::now();
$end = $start->addYears($request->planDetails['duration']);
return response([
'start' => $start,
'end' => $end,
]);

How to use timezones in Laravel?

The user creates date in format like as: 12/23/2016 22:10
After this data should be sent convert to another timezone, for example GMT + 2:
12/23/2016 00:10
I can assume the date that I create should be saved in GTM 0, only after I can change timezone.
How can I use this mechanism in Laravel?
You can use Carbon to change the the timezone of a date as:
$date = Carbon\Carbon::parse('12/23/2016 22:10', 'GMT');
And to add +2 you can do as:
$date->addHours(2)
You can change the timezone for your application in: /config/app.php,
The default timezone is UTC. You can find all supported timezones here: http://php.net/manual/en/timezones.php
Mostly I'm agree with Amit Gupa answer, but the best way to manage timezone conversion isn't by adding hours, but by converting it on Carbon:
$yourdate->timezone('somecountrytimezone')
This way you won't have to worry about different time management between countries (Like daylight saving time) and just manage to get your works done.
Please refer do the documentation : http://carbon.nesbot.com/docs/#api-settersfluent
We can use parse and createFromFormat methods of Carbon to set our datetime as a certain timezone then use setTimezone to convert it to another timezone.
$date = "2022-08-05 12:00:00"; //set datetime for checking
$now = Carbon::now()->timezone('Europe/London')->format('Y-m-d H:i:s');
$createFrom = Carbon::createFromFormat('Y-m-d H:i:s', $date, 'Asia/Hong_Kong')->format('Y-m-d H:i:s');
$parse = Carbon::parse($date,'Asia/Hong_Kong')->setTimezone('Europe/London')->format('Y-m-d H:i:s');
$converted = Carbon::parse($date,'Asia/Hong_Kong')->timezone('Europe/London')->format('Y-m-d H:i:s');
outputs: when dd($now,$createFrom,$parse,$converted);
^ "2022-08-05 08:33:48"
^ "2022-08-05 12:00:00"
^ "2022-08-05 05:00:00"
^ "2022-08-05 05:00:00"
that's not related to laravel , it's just a php , so you can simply get the time-zone offset (exp GMT+3) then do like this :
$timeZoneOffset ---> for GMT+3 you put (3)
function getNewDateByTimeZone($date, $timeZoneOffset)
{
/* if the client Time zone is GMT */
if (!$timeZoneOffset || $timeZoneOffset == 0) {
$timeZoneOffset = "-0";
}
$op = $timeZoneOffset[0];
$timeZoneOffset = preg_replace('/[^0-9.]+/', '', $timeZoneOffset) * 60;
$userDate = date($date, time());
$timeStamp = strtotime($userDate);
$offsetTime = $op == '-' ? $timeStamp + $timeZoneOffset : $timeStamp - $timeZoneOffset;
return date("Y-m-d H:i", $offsetTime);
}
so like that you will save the date in GMT-0

Retrieving date format with am/pm in codeigniter

I have converted date to my local time as below:
$this->date_string = "%Y/%m/%d %h:%i:%s";
$timestamp = now();
$timezone = 'UP45';
$daylight_saving = TRUE;
$time = gmt_to_local($timestamp, $timezone, $daylight_saving);
$this->updated_date = mdate($this->date_string,$time);
And I'm storing this field in to database.
Now at retrieval time I want format like this:
"11-04-2011 4:50:00 PM"
I have used this code:
$timestamp = strtotime($rs->updated_date);
$date1 = "%d-%m-%Y %h:%i:%s %a";
$updat1 = date($date1,$timestamp);
But this will give me only
"11-04-2011 4:50:00 AM"
But I have stored it like it was PM.
Might get voted down, but will have a go at it.
Is it because the MySQL stores it in 24 hour format? (assuming you are using the datetime field type)
Maybe this will help
Converting mysql TIME from 24 HR to AM/PM format
sorry if it doesn't.

Resources