Codeigniter Start and End Date Validation - php

I get the accurate result if i set the start date and end date when the year is 2017. But when the Start date in 15-October-2016 to 15-September-2017 it is not working and show the error message-
$error = "End date can't be older than begin date ";
Here is my code
$data['beginDate'] = $this->input->post('beginDate');
$data['endDate'] = $this->input->post('endDate');
if($data['endDate'] < $data['beginDate']){
$error = "End date can't be older than begin date ";
$this->session->set_flashdata('error', $error);
redirect('/search');
}
else{
$this->load->model('personhistory');
$data['rets'] = $this->personhistory->searchDetails();
$data['sum'] = $this->personhistory->searchDetailsSum();
$data['title'] = "Search Details";
$this->load->view('search_results', $data);
}
Is there any solution to get rid of this problem? Please Help...

PHP does not know what your strings are, and if the values are coming from posted data, then they are strings:
// These are strings
$s1 = '15-October-2016';
$s2 = '15-September-2016';
Instead, you need to create datetime objects for your comparison
$d1 = new DateTime('15-October-2016');
$d2 = new DateTime('15-September-2016');
if( $d1 < $d2 )
echo 'First date comes before the second date';
if( $d1 > $d2 )
echo 'First date comes after the second date';
if( $d1 == $d2 )
echo 'First date and second date are the same';
Try this code and alter the dates, and you will see I am right.
UPDATE:
Technically you could also use strtotime
<?php
$s1 = strtotime('15-October-2016');
$s2 = strtotime('15-September-2016');
if( $s1 < $s2 )
echo 'First date comes before the second date';
if( $s1 > $s2 )
echo 'First date comes after the second date';
if( $s1 == $s2 )
echo 'First date and second date are the same';

Related

Get GMTdate from timestamp in PHP

Here, I am getting encrypted_string dynamically and want to check that it is from last one minutes time interval or not. For that i am using difference between two timestamps (start_time and end_time).
I am not getting proper date format in date_string.
How do i get date_string in gmdate format?
$key = "abc";
$current_date = gmdate("Y_m_d_h_i_s");
$encrypted_string = hash_hmac('sha256',$current_date,$key);
$start_time = date("Ymdhis",strtotime($current_date));
$end_time = date("Ymdhis",strtotime($current_date)-59);
for($i=$start_time; $i > $end_time; $i--){
$date_string = gmdate("Y_m_d_h_i_s",strtotime($i));
$new_string = hash_hmac('sha256', $date_string,$key);
if($encrypted_string == $new_string){
return true;
}
}
Thanks for your time.

How to show leave expiry date of an employee

First I count the number of days between leave dates and resume date e.g. From 26–July-2019 To 31-July-2019 is 5 days. Then I need to know the number of days counting from the leave date to the current date and store in a variable named $count_days. if the no of leave days minus count_days is equal zero then I would say your leave has expired.
I could not figure it out how to get it right
<?php
// include the file that defines (contains) the username and password
require_once("includes/mysqlconn.php");
// build qry
$qry = "SELECT employee.emp_num,employee.emp_lname,employee.emp_fname,eleave.leave_date,eleave.resume_date from employee INNER JOIN eleave ON employee.emp_num = eleave.emp_num where employee.emp_num = '".$_SESSION['empno']."'";
$records = mysqli_query($dbconn,$qry) or die('Query failed: ' . mysqli_error($dbconn));
$time_current = time();
while ($line = mysqli_fetch_array($records))
{
$leavedate = strtotime($line['leave_date']);
$resume_date = strtotime($line['resume_date']);
//count days between dates to get no of leave days
$leave_days = ceil(abs($resume_date - $leavedate) / 86400);
//this is to get days difference between no of leave days and the current day
//when echo $count_days give me -1564264800 I don't know what this value stand for
$count_days = $leavedate - strtotime($time_current);
if (($leave_days-$count_days) <> 0){
echo "enjoy your leave";
}else{
echo "your leave has expired";
}
}
mysqli_close($dbconn);
?>
First of all, $time_current is already in 'time' (integer) format, so strtotime($time_current) is probably NOT what you want to do. Second, if you are checking whether resume_time has passed (aka their leave is over), all you have to do is:
if( $time_current < $leave_time ){
echo 'your leave has not started';
}elseif( $time_current > $resume_time ){
echo 'your leave has expired';
}else{
echo 'enjoy your leave';
}
Otherwise, if you want to know the number of days between, correctly subtract (already integer) $time_current and $resume_date and divide by 86400. For the sake of ease (and understanding) I have wrapped this into a function for you:
function numDaysBetweenTimes(int $time1, int $time2 = null) : int{
if( !$time2 ){
$time2 = time();
}
return ceil(abs($time1 - $time2) / 86400);
}
Example usage:
$line['leave_date'] = '2019-01-15 00:00:00';
$line['resume_date'] = '2019-01-05 00:00:00';
$time_current = time();
$leaveTime = strtotime($line['leave_date']);
$resumeTime = strtotime($line['resume_date']);
echo numDaysBetweenTimes($leaveTime, $resumeTime) . ' leave days<br/>';
echo numDaysBetweenTimes($resumeTime) . ' days between leave and now<br/>';
Output:
4 leave days
202 days between leave and now

Validate date month and year

I have a date in the form MM-YYYY (e.g: 04-2000). I exploded the date into month and year and am now trying to check certain conditions on the month:
between 1 and 12
formed of 2 digits)
and on the year:
formed of 4 digits
Is my syntax correct?
list($name_month, $name_year) = explode('-', $name_date, 2);
if(($name_month < 1 || $name_month > 12 || $name_month ) || ($name_year)) {
echo "<br><br>Wrong date";
$uploadOk = 0;}
You can use the DateTime object and createFromFormat() to validate your date:
$date = '04-2000';
// Create a DateTime object pointing to the 1st of your given month and year
$d = DateTime::createFromFormat('d-m-Y', '01-' . $date);
if($d && $d->format('m-Y') == $date){
echo 'Valid date';
}
Eval.in
This should work, if seprator is always -
$date = '04-2000';
if($date == date('m-Y', strtotime('01-'.$date)))
{
echo 'Valid date';
}
As commented, there are several was to do this. What first comes to mind is checkdate() and createFromFormat().
The catch is, you need to be mindful what is injected for the day part since your format does not include day.
Since createFromFormat() injects the day part from the current date, it is not a viable option. George's code will fail for a format of 02-2015 on days after 28.
As such, I would use checkdate():
$date = '04-2000';
list($month, $year) = explode('-', $date);
if (checkdate($month, 1, $year)) {
echo 'Valid date';
}

Stuck with date compare in php

<?php
date_default_timezone_set('America/Los_Angeles');
$urlYear = '2013';
$currentYear = date('Y');
$systemDate = date('d-m-Y');
if ( ($systemDate >= '01-06-'.$currentYear) || ($currentYear < $urlYear) ) {
echo 'Here are your results <br>';
echo 'System Date '.$systemDate.' '.$currentYear.' '.$urlYear;
} else {
echo 'No results for you';
}
?>
What I'm trying to achieve is:
(If the current date as formatted by me is >= '01-06'-year of the current year)
OR
(if the $currentYear < $urlYear)
//echo 'Here are your results';
But I seem to be getting true for everything. Can you pls help?
You can compare date after converting it to unix timestamp using strtotime,
if ( (strtotime($systemDate) >= strtotime('01-06-'.$currentYear)) || ($currentYear < $urlYear) ) {
echo 'Here are your results <br>';
echo 'System Date '.$systemDate.' '.$currentYear.' '.$urlYear;
} else {
echo 'No results for you';
}
DEMO.
Format your date strings YYYYmmdd when you compare, it will act like an incremental INT. With that, comparing would be easier.
$systemDate = date('Ymd');
Hope this helps.
Why don't you create DateTime objects with the dates you have and compare these
$UrlYear = new DateTime('2013' . '-01-01');
$CurrentYear = new DateTime(date('Y') . '-01-01');
$SystemDate = new DateTime();
if ( ($SystemDate >= $CurrentYear) || ($CurrentYear < $UrlYear) ) {
echo 'Here are your results <br>';
echo 'System Date '. $SystemDate->format('d/m/Y') .' '. $CurrentYear->format('Y') .' '. $UrlYear->format('Y');
} else {
echo 'No results for you';
}
compare date time using timestamp format, use mktime function to convert your date time to timestamp format
You are comparing strings lexically. This doesn't work with formatted date strings.
Transform everything to unix timestamps (UTC) and compare numbers or use date_diff functions
You can use date for comparison but it should be in Y-m-d format:
$systemDate = date( 'Y-m-d' );
$targetDate = date( 'Y-m-d', mktime( 0, 0, 0, 6, 1 ) );
if ( $systemDate >= $targetDate ) {
}

php compare YYYY-mm-dd strings in php

I have run across php code the compares dates in YYYY-mm-dd format as strings. Does this work? It seems to work in simple cases, but I am not sure it makes sense to compare them as strings.
<?php
$today = '2013-02-11';
$start_date = '2013-02-11';
$end_date = '2013-02-12';
$on_promo = (($start_date <= $today) && ($end_date >= $today));
if ($on_promo)
{
echo 'ON promo';
}
else
{
echo 'OFF promo';
}
?>
You're soooooo close. Just use DateTime. It's perfect for this;
<?php
$today = new DateTime('2013-02-11');
$start_date = new DateTime('2013-02-11');
$end_date = new DateTime('2013-02-12');
$on_promo = (($start_date <= $today) && ($end_date >= $today));
if ($on_promo)
{
echo 'ON promo';
}
else
{
echo 'OFF promo';
}
?>
See it in action
When comparing strings in PHP using greater than or less than, it compares them in alphabetical order.
Alphabetically 2013-02-10 comes before 2013-02-13
If we have:
$date1 = '2013-02-10';
$date2 = '2013-02-13';
var_dump($date2 > $date1); // produces true
var_dump('apple' > 'banana'); // produces false
However, note that if the strings are both numerical, it will cast them both to integers
var_dump('11' > '101'); // produces false
var_dump('a11' > 'a101'); // produces true
var_dump('11a' > '101a'); // produces true
Therefore if using the format YYYY-MM-DD you can compare two dates perfectly fine, however I really don't recommend relying on this. Someone might throw in a date like 2013-2-11 (note the month doesn't have the leading 0) and it will completely throw off the logic. It is much better to take John Conde's suggestion and use DateTime
use strtotime instead of comparing dates as strings
<?php
$today = date('U');
$start_date = strtotime('2013-02-11');
$end_date = strtotime('2013-02-12');
$on_promo = (($start_date <= $today) && ($end_date >= $today));
if ($on_promo)
{
echo 'ON promo';
}
else
{
echo 'OFF promo';
}
?>

Categories