strtotime in php not giving exact time - php

I want to compare time from db with current time. strtotime for storing time in db is working fine. but when i use strtotime to get current time it is not giving me exact time. i checked that from an online website. here is my code:
This part store time in db:
public function Add($data)
{
foreach ($data['check'] as $key => $value) {
foreach ($value['in'] as $k => $v) {
if(!empty($value['in'][$k])) {
$allocate = array(
'check_in' => strtotime(date('h:i A', strtotime($value['in'][$k]))),
'check_out' =>strtotime(date('h:i A', strtotime($value['out'][$k]))),
//'check_in' => strtotime($value['in'][$k]),
//'check_out' =>strtotime($value['out'][$k]),
'Days_id' => $key,
'User_id' => $data['Users']
);
$this->db->insert('assgin_days',$allocate);
}
}
}
}
This part compare time from db with current time:
public function checkuserlogin()
{
$string = exec('getmac');
$mac = substr($string, 0, 17);
$day_of_week = date('N');
date_default_timezone_set("Asia/Karachi");
$time = strtotime(date('h:i A'));
$timee = date('h:i A');
$id=$this->user_model->userInfo("id");
$data=$this->db->query("SELECT admin.first_name, days.d_name FROM assgin_days INNER JOIN admin ON admin.id= assgin_days.User_id inner join days ON days.D_id= assgin_days.Days_id where assgin_days.User_id = $id and assgin_days.Days_id =$day_of_week and assgin_days.check_in =<$time and assgin_days.check_out >=$time and assgin_days.is_delete=0")->result_array();
}

need to use date('G:i', strtotime($value['in'][$k])), instead of date('H:i', strtotime($value['in'][$k])), it will change the date into 24 hrs formats then it can easily store and comparable.
public function Add($data){
foreach ($data['check'] as $key => $value) {
foreach ($value['in'] as $k => $v) {
if(!empty($value['in'][$k]))
{
$allocate = array(
'check_in' => date('G:i', strtotime($value['in'][$k])),
'check_out' =>date('G:i', strtotime($value['out'][$k])),
'Days_id' => $key,
'User_id' => $data['Users']);
$this->db->insert('assgin_days',$allocate);
}
}
}
}

Related

How to sort data between two dates using query() function in laravel

Here is my controller:
$my_query = Deathregister::query();
foreach ($request->query() as $key => $value)
{
$my_query->where($key, $value);
}
$my_query->get();
Now if i pass 'fromdate = 2020-10-30' and 'todate = 2021-11-07' i want all the data in bwtween these days. Is this possible?
You can use CarbonPeriod class of PHP.
To use it in Laravel
import it first
use Carbon\CarbonPeriod;
Then in the controller function use
$period = CarbonPeriod::create($request->from_dt,'1 day', $request->to_dt);
foreach ($period as $value) {
$reqDate = $value->format('d-M-Y');
//$reqDate will have the date you can change the format as per your requirement
}
You can use whereDate() method:
Deathregister::whereDate('date_field','>=', $request->input('fromdate'))
->whereDate('date_field','<=', $request->input('todate'))
->get();
The below code worked for me to sort date by given all the parameter with date.
$q = $request->query();
if ($q != NULL) {
$fromdate = $request->fromdate;
$todate = $request->todate;
$my_query = Movementregister::query();
if ($fromdate != NULL and $todate != NULL) {
if (!empty($q['type'])) {
$my_query->where('type', $q['type']);
}
if (!empty($q['issue'])) {
$my_query->where('issue', $q['issue']);
}
$my_query->whereBetween('created_at', [$fromdate, $todate]);
} else {
foreach ($request->query() as $key => $value) {
$my_query->where($key, $value);
}
}
$data = $my_query->get();
return response()->json(["message" => "Success", "data" => $data], 200);
}

PHP compare current time with times in array and return related value

I need to compare current time with times in array and accordingly return related value.
So I have array like this:
$class[0]["start"] = 80000;
$class[0]["end"] = 80500;
$class[0]["title"] = "Warmup";
$class[1]["start"] = 80501;
$class[1]["end"] = 85000;
$class[1]["title"] = "1. class";
$class[2]["start"] = 85001;
$class[2]["end"] = 90000;
$class[2]["title"] = "Break";
And I need compare it with current time:
$time = (int) date('Gis');
I could do it the hardcoded way like this :
if($time >= $class[1]["start"] && $time <= $class[1]["end"]) {
$title = $class[1]["title"];
} elseif($time >= $class[2]["start"] && $time <= $class[2]["end"]) {
$title = $class[2]["title"];
etc ...
but I believe there is a better way how to return the "title" of the class without writing hundreds lines of elseif.
Any idea?
Thanx
Maros
You could just do this..
<?php
$time = (int) date('Gis');
$class[0]["start"] = 80000;
$class[0]["end"] = 80500;
$class[0]["title"] = "Warmup";
$class[1]["start"] = 80501;
$class[1]["end"] = 85000;
$class[1]["title"] = "1. class";
$class[2]["start"] = 85001;
$class[2]["end"] = 90000;
$class[2]["title"] = "Break";
foreach($class as $val){
if($time >= $val["start"] && $time <= $val["end"]) {
$title .= $val["title"];
}
}
echo $title;
?>
Expanding on El_Vanja's comment, you could just split looping your array and filtering its data in two separate functions, so your code becomes both more sparse and more readable.
For example, given your array:
$class = [
[
"start" => 80000,
"end" => 80500,
"title" => "Warmup",
],
[
"start" => 80501,
"end" => 85000,
"title" => "1. class",
],
[
"start" => 85001,
"end" => 90000,
"title" => "Break",
],
];
You could do something like this:
function is_between(int $value, int $low, int $high) {
return ($value >= $low && $value <= $high);
}
function filter(array $data, int $time) {
foreach ($data as $row) {
if (is_between($time, $row['start'], $row['end'])) {
return $row;
}
}
}
And simply call it like this:
var_dump(filter($class, 80100));
var_dump(filter($class, 86000));
var_dump(filter($class, 80600));

Save the results of the date difference on PHP

how to save the results of the date difference to be saved to the database ?
public function save(){
$item = $this->input->post('item');
$date_in = $this->input->post('date_in'); //date in
$date_out = $this->input->post('date_out'); // date out
$hasil = $date_in->diff($date_out);
//echo $hasil->format('%a'); I will save these results to the database
$data_insert = array(
'item' => $item,
'date_in' => $date_in,
'date_out' => $date_out,
'selisih' => $hasil
);
//url save
}
String don't have method diff, diff is the method of DateTime, you need to change string to DateTime.
And it will return DateInterval object, you can get the total days by format('%a') and insert to database;
$hasil = (new DateTime($date_in))->diff(new DateTime($date_out));
$hasil = $hasil->format('%a');
$data_insert = array(
'item' => $item,
'date_in' => $date_in,
'date_out' => $date_out,
'selisih' => $hasil
);
$this->db->insert('mytable', $data_insert);
If you want to get difference you can get it with Carbon easily using diffInDays Example code for you :
$first = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', $date_in);
$second = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', $date_out);
$diff_in_days = $second->diffInDays($first);
Or get it without Carbon :
$first = new DateTime($date_in);
$second = new DateTime($date_out);
$interval = $first->diff($second);

Check if value exists in php multi-dimensional array before adding

I have a separate set of functions that grabs a "Date" and a "Time" from my application and puts the date into as a key, and the time as a multi-dimensional value.
For example purposes:
$alldatetimes = array(
'date1' => array('13:00','14:30','14:30','14:30','15:00'),
'date2' => array('09:00','10:00','10:30','10:30','12:00')
);
foreach ($alldatetimes as $date => $times) {
echo '<h1>This Exports:</h1>';
echo '<h2>'.$date.'</h2><br>';
foreach ($times as $time) {
echo $time.'<br>';
}
}
This exports:
date1
13:00
14:30
14:30
14:30
15:00
date2
09:00
10:00
10:30
10:30
12:00
I'm trying to control if the time is put into the array so only one value each is in the array (I don't want 3 instances of 14:30 for that date).
Based on other posts here I tried to build something like this to identify if the value was there, but I can't figure out how to tie it all together:
function searchForId($id, $array) {
foreach ($array as $date => $times) {
foreach ($times as $time) {
if ($time === $id) {
return $time;
}
}
}
return null;
}
Any ideas?
Update: Here is how the array is initially being created - this probably can be more efficient:
while ($schedule_q -> have_posts() ) : $schedule_q->the_post();
$alldatetimes [get_the_date()][] = get_the_time();
endwhile;
You can add a array_unique() call over each sub-array before you loop over your results to ensure it's all unique:
foreach ($alldatetimes as &$row) {
$row = array_unique($row);
}
Output:
<h1>This Exports:</h1>
<h2>date1</h2><br>
13:00<br>
14:30<br>
15:00<br>
<h1>This Exports:</h1>
<h2>date2</h2><br>
09:00<br>
10:00<br>
10:30<br>
12:00<br>
It is not shown in your question, but how about modifying your function that builds the date/time array to use the times as keys instead of values? Using something like
$alldatetimes[$date][$time]++
in that function would give you an array with one value for each time that would be the number of occurrences of that date/time combination, like this:
$alldatetimes = array(
'date1' => array('13:00' => 1,'14:30' => 3,'15:00' => 1),
'date2' => array('09:00' => 1,'10:00' => 1,'10:30' => 2,'12:00' => 1)
);
Then you could change your code that prints them out to use the key.
foreach ($times as $time => $count) {
echo $time.'<br>';
}
You can write a recursive function
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}

Increment value in array php

I am trying to make a function that grabs all the days that have events that are in a database for a certain user. For instance if there were two events on Jan 23, 2013 it would add Jan 23, 2013 to the array. I got it to work so it adds all the days (without adding the same day twice) but now I want to be able to say how many dates are on each day. So on Jan 23, 2013 it would say they have two events in that day.
I hope this makes sense... I have some code for further aid.
PHP Function (grabbing each day that has events)
//gets upcoming days that have events for a user
public function get_upcoming_days_with_events() {
$return_array = array();
$date_in=null;
$user_id = $this->session->userdata('id');
$query =$this->db->select()->from('events')->where('user_id', $user_id)->get();
foreach ($query->result_array() as $event => $row) {
$date = strtotime($row['date_due']);
if (sizeof($return_array) != 0) {
foreach ($return_array as $date_in_array => $row) {
$d = $row['full_date'];
if (date('Y-m-d', $date) == $d) {
//date is already in array
//increment the number of assignments on this day
$row['number_of_assignments'] += 1;
$date_in = true;
} else{
$date_in = false;
}
}
}
if ($date_in == false) {
$return_array[] = array(
'day' => date('d', $date),
'month' => date('m', $date),
'full_date' => date('Y-m-d', $date),
'number_of_assignments' => 1
);
}
}
return $return_array;
}
So with this I want to be able to increment $return_array['number_of_assignments'] if my function notices that a certain day has more than one event.
Let me know if you need any more info...
Thanks! :)
We can save the info in return_array by index of date, if the date info have not been set into return_array, we make an empty info. Each time, we simply increase number_of_assignments.
public function get_upcoming_days_with_events()
{
$return_array = array();
$user_id = $this->session->userdata('id');
$query =$this->db->select()->from('events')->where('user_id', $user_id)->get();
foreach ($query->result_array() as $event => $row)
{
$date = strtotime($row['date_due']);
$date_key = date('Y-m-d', $date);
if (!isset($return_array[$date_key]))
{
$new_item = array(
'day' => date('d', $date),
'month' => date('m', $date),
'full_date' => $date_key,
'number_of_assignments' => 0,
);
$return_array[$date_key] = $new_item;
}
$return_array[$date_key]['number_of_assignments']++;
}
$return_array = array_values($return_array);
return $return_array;
}
Function: array_count_values() can help you with this, it gives total number of occurance of a value in an array.
For example:
$a = array("apple", "banana", "apple");
var_dump(array_count_values($a));
Will output
array(
[apple] => 2,
[banana] => 1
);
So instead of trying to filter out duplicate events, add them all on the array and then use array_count_values() at last to know their occurenses.

Categories