I store in my database a date format like this:
2017-02-22 16:55:40
I added it to my database like this:
Carbon::now();
I need to check if 4 hours passed since this date.
How I can do this? I couldn't figure out how I can convert this format into Carbon or timestamp.
If you are using Laravel and the date is a Carbon instance from a Model you have access to the whole Carbon API.
You can use the Difference API of Carbon for this specific purpose.
echo $model->thedate->diffInHours($now, false);
If your model does not threat the date as a carbon instance you can cast it by adding the date to the dates array of the current model like so
protected $dates = [
'field_name',
];
Check out Date casting for more information
Update with an explicit example
$user = User::first();
// This will return the difference in hours
$user->created_at->diffInHours(Carbon\Carbon::now(), false);
You can convert it to a Carbon object with:
Carbon::parse('2017-02-22 16:55:40');
Related
I have been trying to get the the Year and Month from the user and insert them into the database.
i am using input type month so that the user can send only the Year and the Month.
<input type="month" name="date_from"/>
<input type="month" name="date_to"/>
and this is my model
function setDateFromAttribute($value)
{
$this->attributes['date_from'] = \Carbon\Carbon::createDateFromFormat('Y-m', $value);
}
function setDateToAttribute($value)
{
$this->attributes['date_to'] = \Carbon\Carbon::createDateToFormat('Y-m', $value);
}
protected $fillable = [
'date_from',
'date_to',
];
and data is saved as 0000.00.00
the data type in my database for these two inputs is
timestamp
i do not know what i am doing wrong here. please help
I don't see createDateFromFormat as a valid Carbon method in the documentation https://carbon.nesbot.com/docs/
Likewise, there does not appear to be any createDateToFormat method.
Carbon::createFromFormat() returns a Carbon object, not a string or equivalent MySQL timestamp, so, assuming you change your code to be:
$this->attributes['date_from'] = \Carbon\Carbon::createFromFormat('Y-m', $value)->toDateTimeString();
It should provide the results you are looking for.
References:
Converting a carbon date to mysql timestamp.
#Ted Stresen-Reuter
Sorry for the late reply couldn't find a solution that works within the model. tried your method which i have tried before with minor changes.
thanks a lot for trying to help me.. i found a method to complete this inside the controller which i will not recommend, but this was the best i was able to find which works and i was on a tight schedule.
'date_from' => isset($date_from[$key]) ? date('Y-m-d h:i:s', strtotime($date_from[$key])) : '',
'date_to' => isset($date_to[$key]) ? date('Y-m-d h:i:s', strtotime($date_to[$key])) : '',
the type timestamp accepts at least dates in full formats. as i know how i pass the data from blade to the controller i was able to add a date method and within it a strttotime method to convert my YY-MM into YY-MM-DD and the date that is inserted by default will be 01.
I have some timestamp records on the DB that have trailing milliseconds at the timestamp and some not have. How to allowing that trailing data (millisecond) in carbon? Is this possible?
Here's the sample of my data
I can't always change the data manually because there are some other services using the same database and sometimes storing timestamp with trailing milliseconds.
As you are using Postgres, your timestamp probably has TIME WITH TIMEZONE
Example: "2018-04-19 07:01:19.929554".
In Such case have to add a date Mutator to your Model.
In your Model add this field for date mutator:
protected $dateFormat = 'Y-m-d H:i:sO';
Alternate Solution:
As you have a mix of timestamps with and without milliseconds I suggest you try this solution using Laravel field mutators:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Parse the created at field which can optionally have a millisecond data.
*
* #param string $created_at
* #return Carbon::Object
*/
public function getCreatedAtAttribute($created_at)
{
// Try to remove substring after last dot(.), removes milliseconds
$temp = explode('.', $created_at);
// If created_at had milliseconds the array count would be 2
if(count($temp) == 2) {
unset($temp[count($temp) - 1]); // remove the millisecond part
} else {
$temp = [$created_at]; // created_at didnt have milliseconds set it back to original
}
return Carbon::parse(implode('.', $temp))->format('Y-m-d H:i:s')
}
}
I have observed in Laravel, storing datetime in database ignores
millisecond field, probably depends on version and db server type.
Also Laravel has whereData() and whereTime() query builders but we
need something like whereDateTimeTz() in all cases.
I recommend storing datetime as unix timestamps in database.
From user timezone convert to GMT and save it to db as millis-timestamp
Carbon::parse('date', 'user_timezone')->setTimezone('GMT')->getPreciseTimestamp(3);
While displaying just convert the db timestamp (GMT) back to user timezone including DST status.
Laravel 7 provides better date parsing by falling back to Carbon::parse if the recevied timestamp from the database doesn't match the expected $dateFormat.
PR: https://github.com/laravel/framework/pull/30628
There are few ways that I can do this using PHP but I could not find a way to do that using laravel specific way.
I have a time that is coming from database in below format: Y:M:s
ex: 05:15:00
This is what I want to do:
add 30 minutes to that date, according to above example result should be: 05:45:00
Below is my current code and I want to add 30min to $endTime:
//get database value according to selected date
$allocatedDateQuery = DB::table('appointments')->where('date', $request->date)->get();
//loop throug every record to get time
foreach ($allocatedDateQuery as $value) {
$time = $value->time;
$endTime = $time;
}
I just got a perfect solution from here.
Use Carbon extention to simply acheive that.
What you have to do is parse your time to Carbon object and then you can use addMinutes() to do that and then you can format() if you want:
foreach ($allocatedDateQuery as $value) {
$time = Carbon::parse($value->time);
$endTime = $time->addMinutes(30);
$allocateValidateMessage .= Carbon::parse($value->time)->format('H:i') . ' - ' . $endTime->format('H:i') . ' ';
}
Usually I use php's date, you can give this a try
Date("Y:M:s", strtotime("30 minutes", strtotime($value->time))
That is converting your time into a string, adding 30minutes to it and converting it to the date format of your desire
Since you said you are grabbing the date from the database I am assuming you are also using Eloquent to query from the database.
You can use Eloquent Mutator Method in your Database Modal Class to mutate the data like this:
public function getAppointmentsAttribute($value) {
return Date("Y:M:s", strtotime("30 minutes", strtotime($value->time)));
}
You can even add another attribute without mutating the original value using Attribute assignments as well. This method caches your query and reduces database calls. Since you do not need to run local loops on the record your code is much cleaner.
I have a model Users And every time user logges in loggedin_at field is updated.
$user = User::find(1);
$user->token = md5(time());
$user->loggedin_at = date('Y-d-m H:i:s');
$user->save();
return $user;
But I know from experience already that sometimes there is difference between MySQL time and PHP time. So when you use comparisons like time > NOW() - INTERVAL 1 HOUR it might now work correctly because you set date from PHP and compare it from MySQL.
Anyway my question is I want to use NOW() to update my date. I try
$user->loggedin_at = DB::raw('NOW()');
But that does not work. By looking into Eloquent source I've managed out this to work
$user->loggedin_at = new \Carbon\Carbon();
This is what Eloquent uses to alter times.
How to use NOW() to set time?
Should I use NOW() or better continue with Carbon?
It's better to use Carbon, it's what it's there for. Laravel uses it out of the box, and uses it within created_at and updated_at.
If you use Carbon, also, you can synchronize PHP's time and Carbon's "NOW" using the timezone configuration inside of config/app.php.
Furthermore, if you want to change the result you get from Carbon, you can do something like:
$now = Carbon::now(new DateTimeZone('Europe/London'));
//can also be passed as a string
$now = Carbon::now('Europe/London');
I am using laravel 5.0. I am getting data from controller as json. I am having value like this.
{"timstamp_date":"1434360957"},
I need to convert this unix timestamp value as Normal Date Like (15-06-2015) or (15-March-2015).
I have used Date(timstamp_date) but it is showing current time only. Not my timstamp date
You could use:
date("d-m-Y H:i:s", 1434360957);
EDIT
You could try;
var dateTime = new Date(1434360957*1000);
var formatted = dateTime.toGMTString();
https://jsfiddle.net/sp57Lnpf/
Use the date function. You need to specify the format as the first parameter:
date("d-m-Y", $timestamp_date)
http://php.net/manual/en/function.date.php
Laravel also comes with Carbon you could use that if you wanted to for further manipulation of the data if you so required it.
http://carbon.nesbot.com/docs/