Date format conversion issue PHP - php

See the below code returns the output as "Jun".
$date_removed =strtotime('2017-06-07 06:06:44');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;
But the below code returns "Dec" as output.
$date_removed =strtotime('0000-00-00 00:00:00');
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;
Here the month value is null. So the return value should be null. Please let me know the issue in my code?

you could try to do it like this:
try {
$dt = new \DateTime('0000-00-00 00:00:00');
} catch (Exception $e) {
var_dump($e);
}

<?php
date_default_timezone_set("Canada/Central");
$date_removed = mktime(00, 00, 0000);
if($date_removed)
{
$datev = date('Y/m/d',$date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;
}
else
echo "invalid date"; //or whatever you want
?>

strtotime() will return false if the date is invalid so you can check that using the return type:
<?php
$date_removed =strtotime('0000-00-00 00:00:00');
if($date_removed>0)
{
$datev = date('d-m-Y', $date_removed);
$nameOfMonth = date('M', strtotime($datev));
echo $nameOfMonth;
}
else
echo "invalid date"; //or whatever you want

Related

Undefined offset (in function)

I get this error in my dates function
when my in panel this code calls the function fecha,only when it calls the date it throws the error, the status and the amount, if it appears to me.
<h1>Viendo compra de <span style="color:#08f"><?=$nombre?></span></h1><br>
Fecha: <?=fecha($r['fecha'])?><br>
Monto: <?=number_format($r['monto'])?> <?=$divisa?><br>
Estado: <?=estado($r['estado'])?><br>
here is the function
<?php
function fecha($fecha){
$e = explode("-",$fecha);
$year = $e[0];
$month = $e[1];
$e2 = explode(" ",$e[2]);
$day = $e2[0];
$time = $e2[1];
$e3 = explode(":",$time);
$hour = $e3[0];
$mins = $e3[1];
return $day."/".$month."/".$year." ".$hour.":".$mins;
}
?>
You need not to reinvent bicycle, just use PHP built in functions:
<?php
function fetcha($originalDate) {
return date("d/m/Y H:i", strtotime($originalDate));
}
echo fetcha('2020-12-06 10:11:12');
Test PHP code here

Problem in checking when date and time has elapse using timezone

Am trying to create a date and time function to check if a given dateTime and timezone passed but my function is always returning true even when i put a future date.
I have below example class
<?php
class JobTimer{
public function __construct() {
}
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = \DateTime::createFromFormat('M d, Y H:i:s', $startOn, new \DateTimeZone($timezone));
return ($nowTime >= $startTime ? true : false);
}
}
?>
Usage
Everything is returning true, my expectation is to return false if current time based on timezone has not yet elapse or return true when time has elapse or time is now
<?php
$job = new JobTimer();
//if($job->isDateTime("2019-05-02 12:00AM", "Asia/Kuala_Lumpur")){
//if($job->isDateTime("2021-05-02 12:00AM", "Asia/Kuala_Lumpur")){
if($job->isDateTime("2020-05-02 12:00AM", "Asia/Kuala_Lumpur")){
echo "YES";
}else{
echo "NO";
}
?>
In your JobTimer class $startTime is false because your format for DateTime::createFromFormat() does not match the format of the date you are passing in as a parameter and causing it to fail.
M d, Y H:i:s matches May 02, 2020 12:00:00 which is not what you are passing to that class.
You should be using:
$startTime = \DateTime::createFromFormat('Y-m-d H:iA', $startOn, new \DateTimeZone($timezone));
Working code:
class JobTimer{
public function __construct() {
}
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = \DateTime::createFromFormat('Y-m-d H:iA', $startOn, new \DateTimeZone($timezone));
return $nowTime >= $startTime;
}
}
$job = new JobTimer();
if($job->isDateTime("2020-05-02 12:00AM", "Asia/Kuala_Lumpur")){
echo "YES";
}else{
echo "NO";
}
Output:
NO
Demo
Change your function to this:
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = new \DateTime($startOn, new \DateTimeZone($timezone));
return ($nowTime >= $startTime ? true : false);
}
Your argument passed to createFromFormat is wrong, and therefore not creating a DateTime correctly. You can just pass your $startOn and a DateTimeZone to create a instance of DateTime

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

Calculate date before n days of a month

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

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