How to check if a date I passed - php

I'm getting a issue where I can't compare two dates in the format dd/mm/yyyy to check if a date is passed or not. code:
$Today = date('d/m/Y');
$fakturaDate = DateTime::createFromFormat('Ymd', $retrieved_DPFDT3);
if ($fakturaDate < $Today ) {
$x+= $y;
}
I don't know if the format is the problem, but if I could use the current it you be much easier.

Your problem is in that you are comparing string date('d/m/Y') with DateTime object.
Just use DateTime for both dates (-;
$Today = new \DateTime();
$fakturaDate = DateTime::createFromFormat('Ymd', $retrieved_DPFDT3);
if ($fakturaDate < $Today ) {
$x+= $y;
}

Compare dates using php function
if(strtotime($fakturaDate) < strtotime($Today))
Try searching on how to compare dates in php.

Related

Date difference in PHP code does not execute

I have a code in PHP 5.5.11 where I am trying to do the following:
Get today's date in a variable --> $today
Calculate the end of month from a date in a form --> $st_dt_eom
if difference between these 2 dates is more than 5 days then execute a code. The code in the if condition below does not execute.
$today= date();
if($_POST['Submit']=='SAVE')
{
$st_dt=YYYYMMDD($_POST['st_dt'],"-");
$st_dt_eom= datetime::createfromformat('YYYYMMDD',$st_dt);;
$st_dt_eom->modify('last day of this month');
$diff = $today->diff($st_dt_eom);
$diffDays= intval($diff->format("%d")); //to get integer number of days
if($diffDays>5){
redirect("index.php");
}
}
An example:
// 2022-12-19
$today = date('Y-m-d');
// $_POST['st_dt']
$st_dt = '2022-12-31';
function dateDiffDays($today, $st_dt)
{
$today_obj= DateTime::createfromformat('Y-m-d', $today);
$st_dt_eom= DateTime::createfromformat('Y-m-d', $st_dt);
$diff = $today_obj->diff($st_dt_eom);
return $diff->days;
}
// int(12)
$res = dateDiffDays($today, $st_dt);
use var_dump to locate your bug.
A few suggestions to improve your code and produce something workable:
<?php
// Instead of using date(), use a DateTime() then you're comparing two DateTimes later on
$today = new DateTime();
// I'm assuming that your YYYYMMDD function removes "-" from the $_POST['st_dt']
// to provide a date in the format YYYYMMDD (or Ymd in PHP).
// Unfortunately, DateTime doesn't understand that format.
// So I'd change this for keeping Y-m-d (YYYY-MM-DD).
// Or modify your code to return that format!
$st_dt = $_POST['st_dt'];
// Watch out for your cAsE when using PHP functions!
$st_dt_eom = DateTime::createFromFormat('Y-m-d',$st_dt);
$st_dt_eom->modify('last day of this month');
$diff = $today->diff($st_dt_eom);
$diffDays= intval($diff->format("%d"));
if($diffDays > 5){
redirect("index.php");
}

Check if date expression ("d-m" without leading zeros) is today

I want to compare current date's day and month with subscription date's day and month only.
For example:
current date(d-m) = 3-6
And I want compare it with any other d-m
How should I do it in PHP
In my project condition is like birth date in which we don't compare year.
The trick in this is to let the month come first. This way PHP can compare the numbers by highest value. Take a look at the following example:
$aDate = DateTime::createFromFormat('m-d', '05-20');
$bDate = DateTime::createFromFormat('m-d', '06-29');
if ($aDate->format('md') > $bDate->format('md')) {
echo "'aDate' is bigger than 'bDate'";
}
use like
$current_date = date("d-m");
$subscription = "03-06-2016";
$subscription_date = date("d-m", strtotime($subscription));
if($current_date ==$subscription_date)
{
echo "date is equal";
}else
{
echo "date is not equal";
}
If you only need to check if the j-n date is the same as the current date, then you don't need to make more than one function call. Because you are not comparing greater than or less than, the format of your input is unimportant.
Code: (Demo)
$subscription = '29-11';
var_export(date("j-n") === $subscription);
// at the moment, the result is true
j is today's day of the month without any leading zeros and
n is today's month without any leading zeros.
Use DateTime() PHP objects.
Considering you have an array with user info from mysql query result: ($userData['suscriptionDate'])
$today = new DateTime();
$userSuscription = new DateTime($userData['suscriptionDate']);
if ( $today->format('d') == $userSuscription->format('d') && $today->format('m') == $userSuscription->format('m')) {
echo 'Congratulations!!';
}
Use DATE_FORMAT() function to extract part of date:
Ref: http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html#function_date-format
SELECT * from table_name WHERE DATE_FORMAT(subscription_date, '%d-%m') = "05-05";
I think, more elegant way to compare, especially when you have a full date with time is diff function of Datetime class:
$d1 = new Datetime();
$d2 = new Datetime('+3 months +2 days +3 hours');
$diff = $d1->diff($d2);
var_dump($diff->d); // 2
var_dump($diff->m); // 2
// or have a comparison as a string
var_dump($diff->format('Difference is in %R%a days'));
// output: Difference is in 63 days
Enjoy! Link to doc
This may help you
$sdate = $row['subscription_date'];
$date1 = date("m-d");
$date2 = date("m-d",strtotime($sdate)) ;
if ($date1 == $date2) {
}

PHP get time from personal identity number under 1970

I have problem, I can't get time from personal identity number under 1970, I need to solve that, but using time. My function looks like. I don't know which way I can go. Thanks!
function getBirthDayFromRd($rd){
$day = substr($rd,4,2);
$month = substr($rd, 2,2);
$year = substr($rd, 0,2);
if($month>=51 and $month<=62){
$month = $month - 50;
}
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}
strtotime() fails due to its being tied to the Unix epoch which does not support dates prior to 1970. Just use DateTime which can handle pre-1970 dates and convert dates easily:
function getBirthDayFromRd($rd){
$date = DateTime::createFromFormat('ymd',$rd);
if($date->format('Y') > date("Y")) {
$date->modify('-100 years');
}
return $date->format('d.m.Y');
}
DateTime::createFromFormat() parses your date and creates the DateTime object. Then we just call DateTime::format() to format it in the desired format.
update
Just fixed a bug where pre-1970 dates were shown 100 years in the future.
Demo
I solve it another way, but u started me up.
if($year < 70){
$year = $year+1900;
$time = date_create_from_format("d.m.Y", $day.".".$month.".".$year);
return date_format($time, "d.m.Y");
}else{
$time = strtotime($day.".".$month.".".$year);
return date("d.m.Y", $time);
}

php - comparing two date

i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code.
the following code should run if the time is above 23:29 and less then 08:10...
$gettime="04:39"; // getting this from database
$startdate = strtotime("23:29");
$startdate1 = date("H:i", $startdate);
$enddate = strtotime("08:10");
$enddate1 = date("H:i", $enddate);
//this condition i need to run
if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1))
{
echo"ok working";
}
please help me in dis regard
thanks
Make sure your comaring the right types of data, time stamps with time stamps and not w/ strings etc...
$gettime= strtotime("22:00"); // getting this from database
$startdate = strtotime("21:00");
//$startdate1 = date("H:i", $startdate);
$enddate = strtotime("23:00");
//$enddate1 = date("H:i", $enddate);
//this condition i need to run
if($gettime >= $startdate && $gettime <= $enddate)
{
echo"ok working";
}
You are comparing the string with a date.
$gettime is a string and you are comparing it with a time object.
You need to convert $gettime to a time object by calling $gettime = strtotime($gettime), and then you can compare it using > or < like you have above.
Assuming you're receiving the time from the DB in a date format (and not as a string):
change:
if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1))
to:
if($gettime >= strtotime($startdate1) || $gettime <= strtotime($enddate1))
For comparing times, you should use the provided PHP classes
The DateTime::diff will return an object with time difference info:
http://www.php.net/manual/en/datetime.diff.php
You may refer to PHP documentation about DateTime::diff function at their website http://php.net/manual/en/datetime.diff.php
You may also go through this stackoverflow question How to calculate the difference between two dates using PHP?

How to check if a date is in a given range?

If you have a $start_date and $end_date, how can you check if a date given by the user falls within that range?
e.g.
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
At the moment the dates are strings, would it help to convert them to timestamp integers?
Converting them to timestamps is the way to go alright, using strtotime, e.g.
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
check_in_range($start_date, $end_date, $date_from_user);
function check_in_range($start_date, $end_date, $date_from_user)
{
// Convert to timestamp
$start_ts = strtotime($start_date);
$end_ts = strtotime($end_date);
$user_ts = strtotime($date_from_user);
// Check that user date is between start & end
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}
Use the DateTime class if you have PHP 5.3+. Easier to use, better functionality.
DateTime internally supports timezones, with the other solutions is up to you to handle that.
<?php
/**
* #param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
* #param DateTime $startDate Date should be after this date to return true
* #param DateTime $endDate Date should be before this date to return true
* return bool
*/
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
return $date > $startDate && $date < $endDate;
}
$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");
echo isDateBetweenDates($fromUser, $startDate, $endDate);
It's not necessary to convert to timestamp to do the comparison, given that the strings are validated as dates in 'YYYY-MM-DD' canonical format.
This test will work:
( ( $date_from_user >= $start_date ) && ( $date_from_user <= $end_date ) )
given:
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
NOTE: Comparing strings like this does allow for "non-valid" dates e.g. (December 32nd ) '2009-13-32' and for weirdly formatted strings '2009/3/3', such that a string comparison will NOT be equivalent to a date or timestamp comparison. This works ONLY if the date values in the strings are in a CONSISTENT and CANONICAL format.
EDIT to add a note here, elaborating on the obvious.
By CONSISTENT, I mean for example that the strings being compared must be in identical format: the month must always be two characters, the day must always be two characters, and the separator character must always be a dash. We can't reliably compare "strings" that aren't four character year, two character month, two character day. If we had a mix of one character and two character months in the strings, for example, we'd get unexpected result when we compared, '2009-9-30' to '2009-10-11'. We humanly see "9" as being less than "10", but a string comparison will see '2009-9' as greater than '2009-1'. We don't necessarily need to have a dash separator characters; we could just as reliably compare strings in 'YYYYMMDD' format; if there is a separator character, it has to always be there and always be the same.
By CANONICAL, I mean that a format that will result in strings that will be sorted in date order. That is, the string will have a representation of "year" first, then "month", then "day". We can't reliably compare strings in 'MM-DD-YYYY' format, because that's not canonical. A string comparison would compare the MM (month) before it compared YYYY (year) since the string comparison works from left to right.) A big benefit of the 'YYYY-MM-DD' string format is that it is canonical; dates represented in this format can reliably be compared as strings.
[ADDENDUM]
If you do go for the php timestamp conversion, be aware of the limitations.
On some platforms, php does not support timestamp values earlier than 1970-01-01 and/or later than 2038-01-19. (That's the nature of the unix timestamp 32-bit integer.) Later versions pf php (5.3?) are supposed to address that.
The timezone can also be an issue, if you aren't careful to use the same timezone when converting from string to timestamp and from timestamp back to string.
HTH
$startDatedt = strtotime($start_date)
$endDatedt = strtotime($end_date)
$usrDatedt = strtotime($date_from_user)
if( $usrDatedt >= $startDatedt && $usrDatedt <= $endDatedt)
{
//..falls within range
}
Convert both dates to timestamps then do
pseudocode:
if date_from_user > start_date && date_from_user < end_date
return true
In the format you've provided, assuming the user is smart enough to give you valid dates, you don't need to convert to a date first, you can compare them as strings.
Convert them into dates or timestamp integers and then just check of $date_from_user is <= $end_date and >= $start_date
$start_date="17/02/2012";
$end_date="21/02/2012";
$date_from_user="19/02/2012";
function geraTimestamp($data)
{
$partes = explode('/', $data);
return mktime(0, 0, 0, $partes[1], $partes[0], $partes[2]);
}
$startDatedt = geraTimestamp($start_date);
$endDatedt = geraTimestamp($end_date);
$usrDatedt = geraTimestamp($date_from_user);
if (($usrDatedt >= $startDatedt) && ($usrDatedt <= $endDatedt))
{
echo "Dentro";
}
else
{
echo "Fora";
}
You can try this:
//custom date for example
$d1 = new DateTime("2012-07-08");
$d2 = new DateTime("2012-07-11");
$d3 = new DateTime("2012-07-08");
$d4 = new DateTime("2012-07-15");
//create a date period object
$interval = new DateInterval('P1D');
$daterange = iterator_to_array(new DatePeriod($d1, $interval, $d2));
$daterange1 = iterator_to_array(new DatePeriod($d3, $interval, $d4));
array_map(function($v) use ($daterange1) { if(in_array($v, $daterange1)) print "Bingo!";}, $daterange);
I found this method the easiest:
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
$start_date = date_create($start_date);
$date_from_user = date_create($date_from_user);
$end_date = date_create($end_date);
$interval1 = date_diff($start_date, $date_from_user);
$interval2 = date_diff($end_date, $date_from_user);
if($interval1->invert == 0){
if($interval2->invert == 1){
// if it lies between start date and end date execute this code
}
}

Categories