Carbon object to Unix timestamp based on timezone - laravel-5

I have a datetime string of format 'Y-m-d H:i:s', and datetime value as '2018-01-30 07:11:21'.
$carbon_obj = Carbon::createFromFormat('Y-m-d H:i:s' , '2018-01-30 07:11:21','America/Chicago');
How do it get the Unix timestamp from this carbon object?

just add timestamp at the back of your code.
$carbon_obj = Carbon::createFromFormat('Y-m-d H:i:s' , '2018-01-30 07:11:21','America/Chicago')->timestamp;
or
$carbon_obj = Carbon::createFromFormat('Y-m-d H:i:s' , '2018-01-30 07:11:21','America/Chicago');
$carbon_obj->timestamp;
If you have data missing error. missing it is the data your passed it not a complete date format.
Try this.
$timestp = Carbon::createFromFormat('Y-m-d H:i:s', Carbon::parse($trans['transaction_datetime']) ,Setting::get('timezone'))->timestamp;

You can use Carbon::shiftTimezone to change the timezone without changing the dates and time.
$dt = Carbon::parse('2020-03-27');
dump($dt); //2020-03-27 00:00:00.0 Asia/Kolkata (+05:30)
dump($dt->shiftTimezone('utc')); //2020-03-27 00:00:00.0 UTC (+00:00)

Related

Data is not coming in laravel 5.4 after using timestamp in query

Data is not coming when comparing current time between 2 times to fetch data in Laravel. Both times are saved in the database as timestamp and in query also I am using timestamp. Below is the code i wrote:-
$current_date = strtotime(date('d-m-Y H:i:s'));
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get();
"time_from" and "time_to" both timestamps are saved in bigint format in database. I entered timestamp using search option in direct database also still data did not come. Can someone please tell me where i am making mistake.
I think you should swap the time_from to <= and time_to to >, and try
$bookings = MachineBooking::with('userDetail')
->where('machine_id', $machine_id)
->where('time_from', '<=', $current_date) # changed
->where('time_to', '>', $current_date) # changed
->get();
You not describe what database you use. But maybe you can change to Y-m-d H:i:s format:
$current_date = strtotime(date('Y-m-d H:i:s'));
but strtotime is return int not bigint.
I hope I will help you
firstly You must cast the date in Model MachineBooking
protected $casts = ['time_from' => 'datetime:Y-m-d H:i:s',time_to =>'datetime:Y-m-d H:i:s'];
secondly
cast current date with same format of time_from and time_to
$current_date = strtotime(date('Y-m-d H:i:s'));
Please change your code with:
$current_date = strtotime(date('Y-m-d H:i:s'));
time_from and time_to are formatted date not a int . But your $current_date is int with using strtotime method
Just take strtotime method:
$current_date =date('d-m-Y H:i:s');
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get()

Dates comparision not working on my codeigniter model class

$today=date('y-m-d');
$query3 = $this->db->query("SELECT exp_date FROM other_data WHERE id_usr ='$session_id' AND status = 1")->row()->exp_date;
if($query3>=$today){
$lndate =array(
'visits' => $query2 + 1 ,
'login_date' => $today
);
$this->db->update('other_data', $lndate);
}
Here exp_date is a date which is in the same format as $today(date).
Even exp_date > today is false the update statement executes in the model
function of codeIgniter. But it should not execute when the condition is wrong.
The date format matched with database date.
Thanks in advance for the help!
Try like this
$today = date('Y-m-d', strtotime('now')); //Current Date
And make date format same as $today have like this
If your are getting date from database.
After getting the record from the database
$query3 = date('Y-m-d', strtotime($query3));
if($query3 >= $today){
//Condition true
}else{
//Condition false
}

Laravet Carbon date setTimezone(8) giving +0700

I want to set timezone to GMT+8
$data = Carbon::now();
$data->setTimezone(8);
but the result given is
Carbon #1521099609 {#2145
date: 2018-03-15 14:40:09.759487 Asia/Krasnoyarsk (+07:00)
}
I have no idea why it happen, so I must use timezone name to get exact date I want?
Try like this
$data = Carbon::now();
$data->setTimezone('Asia/Krasnoyarsk');
Also make sure to set the timezone else it will have the default value which is set in your php.ini file
Carbon::now(new DateTimeZone('Europe/London'));
Hope this helps
First get the timezone name, then set:
$data = Carbon::now();
$timezoneName = timezone_name_from_abbr("", 8*3600, false);
if($timezoneName)
$data->setTimezone($timezoneName);

Delete a row in databse if has a code that has been present for 15 min

On my model I am trying to make a function so when I reload my page it will check if any rows have a code set and check the date_modified time 2017-02-16 13:53:18 and if has been present for more than 15min will remove row.
Question: On each post The column "code" if has any value then will check the date and time if has been there longer 15 min with code value still present then will remove row.
I have tried this below but when I reload page it does not remove any row.
Model Function
public function clear_unconfirmed_post() {
$this->db->where('code is NOT NULL', NULL, FALSE);
$this->db->where('date_modified < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 15 MINUTE))', NULL, FALSE);
$this->db->delete($this->db->dbprefix . 'post');
}
Controller Construct Area
public function __construct() {
parent::__construct();
$this->load->model('catalog/forum/newthread_model');
$this->newthread_model->clear_unconfirmed_post();
}
Your date_modified field is of type DATETIME and you are comparing it with a integer (that is was UNIX_TIMESTAMP function returns).
I would advise as a general rule of thumb, using UNIX timestamp (i.e - INT fields) directly when storing date-time values, for easier comparisons and for not being affected by timezones, as UNIX timestamps are in UTC (+0), so they can be used very easily for timezones conversions.
So when storing a value in the date_modified field, instead of storing a value like this (the example shows variable assignment in PHP):
$date_modified = date("Y-m-d H:i:s"); // 2017-02-07 10:18:00 in UTC+2 timezone
You will store it like this:
$date_modified = time(); // 1486455515 which equals to 2017-02-07 08:18:00 in UTC
In the mysql query now() will take the server time so it is better to pass it using php
$date = date("Y-m-d H:i:s");
$time = strtotime($date);
$time = $time - (15 * 60);
$date = date("Y-m-d H:i:s", $time);
in model
$this->db->where('date_modified <' $date);

Query builder where between custom date format

My field date (varchar datatype) is in a custom date format it's dd-mm-yyyy.
Example : 01-01-2016
I want to get data between specific dates from a database field date. Let's say input data are stored in variables: startDate & endDate.
I tried with this query but the result are weird.
$query = DB::table('test')->whereBetween('date', array($startDate, $endDate))->get();
I think it fails because I used a custom date format.
How can this be solved?
#updated
let's say i have date like this
29-12-2015
29-12-2015
29-12-2015
30-12-2015
29-12-2015
01-01-2016
06-01-2016
i set $startDate & $endDate like this
$startDate = "01-12-2015";
$endDate = "01-01-2016";
it's even not get any result with this script
$query = DB::table('test')->whereBetween('date', array($startDate, $endDate))->get();
but if I using
$startDate = "01-12-2015";
$endDate = "31-12-2015";
i get all data...which it's wrong result because 2016 data should not in range...it's somehow like not filtered
since your date datatype is varchar you can try to use str_to_date function in mysql then before using $starDate and $endDate variable convert it's format first.
Sample code is like this.
$startDate = date("Y-m-d", strtotime("01-12-2015"));
$endDate = date("Y-m-d", strtotime("31-12-2015"));
$query = DB::table('test')->whereBetween("str_to_date(date, '%d-%m-%Y')", array($startDate, $endDate))->get();
Hope that helps.
The format shouldn't be a problem; Unless the data you POST are in different format from what the database holds. Make sure that the format for the date field in database matches the format to the ones you store in $startDate, $endDate.
Also I would solve this by taking a slightly different approach. This can become a model function, call it getDataBetweenDates(). Each time you need to query the database, to retrieve the data between a specified range of dates, you do a call to this function from the controller:
Model
public function getDataBetweenDates($startDate, $endDate) {
$range = [$startDate, $endDate];
return $this
->whereBetween('date', $range)
->get();
}
Controller
$startDate = Input::get('start_date');
$endDate = Input::get('end_date');
$model = new Model; // use your model name;
$data = $model->getDataBetweenDates($startDate, $endDate);

Resources