Calculate date before n days of a month - php

How to calculate a date before 10 days of every month end ?Am using codeigniter platform.
I need to check whether a date is within 10 days before the end of every month.
Please help

You can try using date_modify function for example see this php documentation
http://php.net/manual/en/datetime.modify.php

i need to check whether a date is within10 days before the end of a month
function testDate($date) {
$uDate = strtotime($date);
return date("m", $uDate) != date("m", strtotime("+10 days", $uDate));
}
echo testDate("2016-03-07") ? "Yes" :"No"; // No
echo testDate("2016-03-27") ? "Yes" :"No"; // Yes

you can create a library with this
class Calculate_days{
function __construct() {
parent::__construct();
}
function calculate( $to_day = date("j") ){
$days_month = date("t");
$result = (int) $days_month - $to_day;
if( $result <= 10){
$result = array("type" => TRUE, "missing" => $result . 'days');
return $result;
}
else{
$result = array("type" => FASLE, "missing" => $result . 'days');
return $result;
}
}
}
controller.php
function do_somthing(){
$this->load->library('Calculate_days');
$result = $this->Calculate_days->calculate(date("j"));
var_dump($result);
}

Related

How to call json from multiple nested if condition

I am using CodeIgniter. I am working on the small project which is a Batch list. Now If an admin wants to create the batch list then should enter the start date and end date and start time and end time then it will check in the database that batch is running on the same date and time? If yes then it will display the message if not then it will create a new batch list.
If the date is the same the time should be different.
Now My logic is,
I am comparing the first new_start_date with exist_start_date and exist_end_date if date found in between then it will check the time.
It's working till date compare. Even it's checking the time but from there how to exit the process and call the JSON? because from there my JSON not working.
I added "echo "time not match";" from there I am not able to call the JSON I am getting the output on my network tab.
I am getitng the output
enter 1enter 2{"error":true,"msg":"Batch Created"}time not match
Would you help me out in this?
$id = $this->input->post('venue_id');
$venue_id = implode(',',$id);
$activity_list_id = $this->input->post('activity_name');
$new_batch_start_date = date('Y-m-d',strtotime($this->input->post('start_date')));
$new_batch_end_date = date('Y-m-d',strtotime($this->input->post('end_date')));
$new_batch_start_time = $this->input->post('start_time');
$new_batch_end_time = $this->input->post('end_time');
$days = implode(',',$this->input->post('days'));
//print_r($days);
if($new_batch_start_date >= $new_batch_end_date)
{
$response['error'] = false;
$response['msg'] = "End Date Should be Greater than Start Date";
echo json_encode($response);
return false;
}
//convert in Time Format
$new_batch_start_time = strtotime($new_batch_start_time);
$new_batch_end_time = strtotime($new_batch_end_time);
$venue = $this->input->post('name');
$data = array(
'activity_list_id' => $this->input->post('activity_name'),
'batch_venue_id' => $venue_id,
'batch_name' => $this->input->post('batch_name'),
'start_date' => date('Y-m-d',strtotime($this->input->post('start_date'))),
'end_date' => date('Y-m-d',strtotime($this->input->post('end_date'))),
'start_time' => $this->input->post('start_time'),
'end_time' => $this->input->post('end_time'),
'total_capacity' => $this->input->post('total_capecity'),
'batch_status' => 1,
'created_by' => trim($this->session->userdata['login_data']['user_id']),
'created_date' => date('d-m-Y h:i:s A'),
'batch_days' => $days
);
$get_batch_details = $this->Batch_model->fetchBatches();
if(!empty($get_batch_details))
{
foreach ($get_batch_details as $rows)
{
$exist_batch_start_date = $rows->start_date;
$exist_batch_end_date = $rows->end_date;
$batch_time1 = strtotime($rows->start_time);
$batch_time2 = strtotime($rows->end_time);
$batch_venue_id = explode(',',$rows->batch_venue_id);
$common_venue_id = array_intersect($id,$batch_venue_id);
//print_r($common_venue_id);
if($common_venue_id)
{
echo "enter 1";
//if new batch start date between existing batch start date
if($exist_batch_start_date <= $new_batch_start_date && $exist_batch_end_date >= $new_batch_start_date ){
echo "enter 2";
if($batch_time1 <= $new_batch_start_time && $batch_time2 > $new_batch_start_time){
$msg = "Other Batch Alredy Running On from Date $batch_start_date to $exist_batch_end_date on Time : $batch_time1 to $batch_time2.
Please Change Time Slot or Start And End Date";
$response['error'] = false;
$response['msg'] = $msg;
echo json_encode($response);
exit;
}
else{
$result = $this->Batch_model->createBatch($data);
echo "time not match";
print_r($result);
}
break;
}
//if date is different
else
{
$result = $this->Batch_model->createBatch($data);
}
}else
{
$result = $this->Batch_model->createBatch($data);
}
}
}
//first time creating batch
else
{
$result = $this->Batch_model->createBatch($data);
}
Mobel
function createBatch($data){
if($this->db->insert('batch_list',$data))
{
$response['error'] = true;
$response['msg'] = "Batch Created";
echo json_encode($response);
}
else
{
$response['error'] = true;
$response['msg'] = "Failed to Create Batch";
echo json_encode($response);
}
}
function fetchBatches()
{
$result = $this->db->where(['batch_list.batch_status'=>1,'activity_list.act_status'=>1])
->from('batch_list')
->join('activity_list','activity_list.activity_id = batch_list.activity_list_id')
->get()
->result();
return $result;
}
Ajax
success: function(response){
var data = JSON.parse(response);
if (data.error == true){
swal({
title: "Success",
text: data.msg ,
type: "success"
}).then(function(){
location.reload();
}
);
} else {
swal({
title: "Warning",
text: data.msg ,
type: "warning"
});
}
}
Would you help me out in this issue?
your entire approach is a bit messy because you find yourself in a ton of redundant code fragments and nobody is able to understand what exactly you want - i gv you some hints here including an example based on your code
Use Exceptions - it's perfect for your case - if something goes wrong - stop it
Try to filter your need to an extent of one single task und try to solve it - and only after that go to the next task
Always - remember always - think about one term - if you find repeatedly the same code in your application - you know something is wrong - and you should refactor it - don't be ashamed about redundancies - they do always happen - but if you find them, you must refactor those code snippets
Now to your example
What are your tasks here ?
you can try to ask your database if a batch is already running - you dont need to iterate over the entire table entries
Compare both input Dates from Administrator - if start date is in the future of end date, instantely stop the application
your intersection isn't really clear to me what you want to achieve here - but i'm really convinced you can ask the database here too (catchword: find_in_set)
Based on that information we can start to develop things now ;) (if i don't have everything just complete the list above and try to implement your task)
Controller:
try
{
$id = $this->input->post('venue_id');
$venue_id = implode(',',$id);
$activity_list_id = $this->input->post('activity_name');
$new_batch_start_date = date('Y-m-d',strtotime($this->input->post('start_date')));
$new_batch_end_date = date('Y-m-d',strtotime($this->input->post('end_date')));
$new_batch_start_time = $this->input->post('start_time');
$new_batch_end_time = $this->input->post('end_time');
$days = implode(',',$this->input->post('days'));
$objDateStart = DateTime::createFromFormat('Y-m-d h:i a', $new_batch_start_date.' '.$new_batch_start_time);
$objDateEnd = DateTime::createFromFormat('Y-m-d h:i a', $new_batch_end_date.' '.$new_batch_end_time);
if ($objDateEnd < $objDateStart) throw new Exception('End Date Should be Greater than Start Date');
if ($this->Batch_model->hasBatchesBetweenDates($objDateStart, $objDateEnd)) throw new Exception('Other Batch already running On from '.$objDateStart->format('d-m-Y H:i').' to '.$objDateEnd->format('d-m-Y H:i').'. Please Change Time Slot for Start and End Date');
$data = array(
'activity_list_id' => $this->input->post('activity_name'),
'batch_venue_id' => $venue_id,
'batch_name' => $this->input->post('batch_name'),
'start_date' => $objDateStart->format('Y-m-d'),
'end_date' => $objDateEnd->format('Y-m-d'),
'start_time' => $objDateStart->format('H:i'),
'end_time' => $objDateEnd->format('H:i'),
'total_capacity' => $this->input->post('total_capecity'),
'batch_status' => 1,
'created_by' => trim($this->session->userdata['login_data']['user_id']),
'created_date' => date('d-m-Y h:i:s A'),
'batch_days' => $days
);
$this->Batch_model->createBatch($data);
}
catch(Exception $e)
{
$arrError = [
'error' => false,
'msg' => $e->getMessage()
];
echo json_encode($arrError);
}
Model:
public function hasBatchesBetweenDates(DateTime $objDateStart, DateTime $objDateEnd)
{
$query = $this->db
->from('batch_list')
->join('activity_list','activity_list.activity_id = batch_list.activity_list_id')
->where('CONCAT(start_date,\' \',start_time) >=', $objDateStart->format('Y-m-d H:i:s'))
->or_group_start()
->where('CONCAT(end_date, \' \', end_time) <=', $objDateEnd->format('Y-m-d H:i:s'))
->where('CONCAT(end_date, \' \', end_time) >=', $objDateStart->format('Y-m-d H:i:s'))
->group_end()
->get();
return ($query->num_rows() > 0);
}
i hope you understand the concepts here - if you've questions - don't hesitate to ask

display record with specific date in codeigniter

I want to select record with certain date and id. My datetime format in database is 2018-02-23 08:38:45. I've try this in my model but it always return the records with specific id only. My date format in $tgl is 23-01-2018 so I change the format using $date = date('Y-m-d', strtotime($tgl) );
public function spesific_odontogram($id_pasien, $date){
$query = "SELECT * FROM odontogram WHERE DATE('inserted_at') = $date AND id_pasien=$id_pasien";
$record = $this->db->query($query);
if ($record->row_array()>0) {
return $record->result_array();
}
return false;
//return $record;
}
Here's my controller
public function spesific_odontogram(){
$id_pasien=$_POST['id_pasien'];
$tgl=$_POST['tgl'];
$date = date('Y-m-d', strtotime($tgl) );
$data['record']=$this->m_pasien->spesific_odontogram($id_pasien, $date);
if ($this->input->is_ajax_request())
{
echo json_encode($data);
exit;
}
}
Use Date variable like '$date' instead of $date. Also make sure date format are same
public function spesific_odontogram($id_pasien, $date){
$query = $this->db->query("SELECT * FROM odontogram WHERE inserted_at = '$date' AND id_pasien=$id_pasien");
if ($query->row_array()>0) {
return $query->result_array();
}
return false;
}
Try using below query on your model :
public function spesific_odontogram($id_pasien, $date){
$query = "SELECT * FROM odontogram WHERE inserted_at >= $date AND inserted_at < $date + INTERVAL 1 DAY AND id_pasien=$id_pasien";
$record = $this->db->query($query);
if ($record->row_array()>0) {
return $record->result_array();
}
return false;
//return $record;
}
It basically check for only matches date record without calculate DATE() value of every row

How to fix the error in codeigniter project?

My error message in codeigniter framework:
A Database Error Occurred
Error Number: 1140
In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'hms.rooms.id'; this is incompatible with sql_mode=only_full_group_by
SELECT `rooms`.*, count(room_no) as total_rooms FROM `rooms` WHERE `room_type_id` = '10'
Filename: D:/Installed_Apps/OpenServer/OpenServer/domains/hms.loc/system/database/DB_driver.php
Line Number: 691
Why is there such an error and how to eliminate it? In what there can be a problem in the code?
In these functions, something is wrong or everything is normal?
function check_availability($check_in,$check_out,$adults,$kids,$room_type_id){
$query = '?date_from='.$check_in.'&date_to='.$check_out.'&adults='.$adults.'&kids='.$kids.'&room_type=';
$CI =& get_instance();
if($check_in==$check_out){
$check_out = date('Y-m-d', strtotime($check_out.'+ 1 day'));
}
$CI->db->where('id',1);
$settings = $CI->db->get('settings')->row_array();
$CI->db->where('id',$room_type_id);
$CI->db->select('room_types.*,base_price as price');
$room_type = $CI->db->get('room_types')->row_array();
//echo '<pre>'; print_r($room_type);die;
$CI->db->where('room_type_id',$room_type_id);
$CI->db->select('rooms.*,count(room_no) as total_rooms');
$rooms = $CI->db->get('rooms')->row_array();
$total_rooms = $rooms['total_rooms'];
//echo '<pre>'; print_r($rooms);die;
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt){
$date = $dt->format( "Y-m-d" );
$dayno = $dt->format( "N" );
$day = $dt->format( "D" );
$day = strtolower($day);
///echo $date;die;
//check for room block period
if($date >= $settings['room_block_start_date'] && $date <=$settings['room_block_end_date'])
{
$block_message = "Sorry.. No Room Available Between ".date('d/m/Y',strtotime($settings['room_block_start_date']))." to ".date('d/m/Y',strtotime($settings['room_block_end_date']))." ";
$CI->session->set_flashdata('error', $block_message);
redirect('');
}
$CI->db->where('O.room_type_id',$room_type_id);
$CI->db->where('R.date',$date);
$CI->db->select('R.*,');
$CI->db->join('orders O', 'O.id = R.order_id', 'LEFT');
$orders = $CI->db->get('rel_orders_prices R')->result_array();
//echo '<pre>'; print_r($orders);die;
//echo $total_rooms;die;
if($total_rooms > 0){
//echo count($orders);die;
if(count($orders) >= $total_rooms){
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
$CI->session->set_flashdata('error', "Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room");
redirect('front/book/index'.$query);
}else{
continue; // continue loop
}
}else{
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
$CI->session->set_flashdata('error', "Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room");
redirect('front/book/index'.$query);
}
}
return;
}
function check_availability_ajax($check_in,$check_out,$adults,$kids,$room_type_id){
$query = '?date_from='.$check_in.'&date_to='.$check_out.'&adults='.$adults.'&kids='.$kids.'&room_type=';
$CI =& get_instance();
if($check_in==$check_out){
$check_out = date('Y-m-d', strtotime($check_out.'+ 1 day'));
}
$CI->db->where('id',1);
$settings = $CI->db->get('settings')->row_array();
$CI->db->where('id',$room_type_id);
$CI->db->select('room_types.*,base_price as price');
$room_type = $CI->db->get('room_types')->row_array();
//echo '<pre>'; print_r($room_type);die;
$CI->db->where('room_type_id',$room_type_id);
$CI->db->select('rooms.*,count(room_no) as total_rooms');
$rooms = $CI->db->get('rooms')->row_array();
$total_rooms = $rooms['total_rooms'];
//echo '<pre>'; print_r($rooms);die;
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt){
$date = $dt->format( "Y-m-d" );
$dayno = $dt->format( "N" );
$day = $dt->format( "D" );
$day = strtolower($day);
if($date >= $settings['room_block_start_date'] && $date <=$settings['room_block_end_date'])
{
$block_message = "Sorry.. No Room Available Between ".date('d/m/Y',strtotime($settings['room_block_start_date']))." to ".date('d/m/Y',strtotime($settings['room_block_end_date']))." ";
return $block_message;
}
$CI->db->where('O.room_type_id',$room_type_id);
$CI->db->where('R.date',$date);
$CI->db->select('R.*,');
$CI->db->join('orders O', 'O.id = R.order_id', 'LEFT');
$orders = $CI->db->get('rel_orders_prices R')->result_array();
//echo $total_rooms;die;
if($total_rooms > 0){
if(count($orders) > $total_rooms){
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
return 'Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room';
}else{
continue; // continue loop
}
}else{
$CI->session->unset_userdata('booking_data');
$CI->session->unset_userdata('coupon_data');
return 'Sorry.. This Dates Between Rooms Not Available Please Try With Another Date Or Room';
}
}
return 1;
}
Here is my Book.php controller code where I use that functions:
function index()
{
//echo '<pre>'; print_r($_GET);
//check availbilty
//get_invoice_number();
$this->session->unset_userdata('booking_data');
$this->session->unset_userdata('coupon_data');
$data['page_title'] = lang('make_reservation');
$data['meta_description'] = $this->setting->meta_description;
$data['meta_keywords'] = $this->setting->meta_keywords;
$data['banners'] = $this->homepage_model->get_banners();
$data['testimonials'] = $this->homepage_model->get_testimonials(); // get 6 testimonials
$data['room_types'] = $this->homepage_model->get_room_types_all();
$data['taxes'] = $this->homepage_model->get_taxes();
if(!empty($_GET['room_type'])){
$data['services'] = $this->homepage_model->get_paid_services($_GET['room_type']);
}
//echo '<pre>'; print_r($data['services']);
if(empty($_GET['room_type'])){
$this->render('book/room_types', $data);
}else{
check_availability($_GET['date_from'],$_GET['date_to'],$_GET['adults'],$_GET['kids'],$_GET['room_type']);
$data['room_type'] = $this->homepage_model->get_room_type($_GET['room_type']);
$this->render('book/view', $data);
}
}
you are facing this problem because of the ONLY_FULL_GROUP_BY option in the MYSQL so kindly set,
SET GLOBAL sql_mode=(SELECT REPLACE(##sql_mode,'ONLY_FULL_GROUP_BY',''));
to solve the issue.
SQL query including aggregate functions like COUNT() or SUM() etc. always have a GROUP BY clause in it. Which specifies the other non-grouped columns in the final resultset.
In you query the following remarks are noted:
You have specified rooms.* which is not recommended while grouping.
You may mention specific columns while grouping, and specify those columns in the GROUP BY clause too.
For example,
SELECT
Count(product_tb.product_id),
product_tb.`name`,
product_tb.details
FROM
`product_tb`
WHERE
product_tb.product_id = 1
GROUP BY
product_tb.`name`,
product_tb.details

php add method incorrectly working

I'm in the process of learning PHP and i'm having some trouble. My function is returning the "milestones" with the same date they were plugged in with. I believe I am using the add() method incorrectly. Thankyou.
PHPplayground: http://www.tehplayground.com/#cARB1wjth
$milestones = null;
$milestones = createMilestone($milestones, true, 10, "15-1-1", "birthday" );
var_dump( $milestones );
function createMilestone($milestones, $forward, $days, $startDate, $milestoneName ){
if ( is_string($startDate)){
$date = DateTime::createFromFormat("Y-m-d", $startDate );
}else if(is_array($startDate) ){
$date = $startDate["date"];
}else{
$date = $startDate;
};
$daysInterval = DateInterval::createFromDateString($days);
if ($forward){
$date->add($daysInterval);
}else{
$date->sub($daysInterval);
}
$milestones[$milestoneName]['date'] = $date;
return $milestones;
}
You need to use :
$daysInterval = DateInterval::createFromDateString($days . ' days');
See the doc here for DateInterval and that page for the diverse date formatting (called relative format) you can use.
And BTW, if you give a DateTime like "15-1-1", the correct format is not "Y-m-d" but "y-m-d" (lowercase 'y')

PHP if based on current system date

Trying to setup a page that auto updates based on the users date/time.
Need to run a promotion for 2 weeks and each day it needs to change the displayed image.
Was reading through http://www.thetricky.net/php/Compare%20dates%20with%20PHP to get a better handle on php's time and date functions.Somewhat tricky to test, but I basically got stuck on:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date() = $dateA){
echo 'todays message';
}
else if(date() = $dateB){
echo 'tomorrows message';
}
?>
I know the above function is wrong as its setup, but I think it explains what I am aiming for.
Time is irrelevant, it needs to switch over at midnight so the date will change anyway.
You seem to need this:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date('Y-m-d') == $dateA){
echo 'todays message';
} else if(date('Y-m-d') == $dateB){
echo 'tomorrows message';
}
?>
you want
<?php
$today = date('Y-m-d')
if($today == $dateA) {
echo 'todays message';
} else if($today == $dateB) {
echo 'tomorrows message';
}
?>
I would go a step back and handle it via file names. Something like:
<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text">
So your script would look something like this:
<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text">
If you're going to do date calculations, I'd recommend using PHP's DateTime class:
$promotion_starts = "2012-07-16"; // When the promotion starts
// An array of images that you want to display, 0 = the first day, 1 = the second day
$images = array(
0 => 'img_1_start.png',
1 => 'the_second_image.jpg'
);
$tz = new DateTimeZone('America/New_York');
// The current date, without any time values
$now = new DateTime( "now", $tz);
$now->setTime( 0, 0, 0);
$start = new DateTime( $promotion_starts, $tz);
$interval = new DateInterval( 'P1D'); // 1 day interval
$period = new DatePeriod( $start, $interval, 14); // 2 weeks
foreach( $period as $i => $date) {
if( $date->diff( $now)->format("%d") == 0) {
echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n";
echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag
break;
}
}
Given that the promotion starts on 07-16, this displays the following, since it is now the second day of the promotion:
Today I should display a message for 2012-07-17 (1)
I would have displayed: the_second_image.jpg

Categories