i am struggling for a long time to set a specific date but i am not getting correct out put.
i want to get date from user and compare that date with the date 15 days older then today. if it is older than 15 days then convert to today else print what it is.
$todaydate= $_GET['date'];// getting date as 201013 ddmmyy submitted by user
$todaydate=preg_replace("/[^0-9,.]/", "", $todaydate);
$today =date("dmy"); //today ddmmyy
$older= date("dmy",strtotime("-15 day")); // before 15 days 051013
if ($todaydate <= $older){
$todaydate= $today;}
problem is, it is taking date as number and giving wrong result.
Comparing date strings is a bit hacky and prone to failure. Try comparing actual date objects
$userDate = DateTime::createFromFormat('dmy', $_GET['date']);
if ($userDate === false) {
throw new InvalidArgumentException('Invalid date string');
}
$cmp = new DateTime('15 days ago');
if ($userDate <= $cmp) {
$userDate = new DateTime();
}
Also, strtotime has some severe limitations (see http://php.net/manual/function.strtotime.php#refsect1-function.strtotime-notesand) and is not useful in non-US locales. The DateTime class is much more flexible and up-to-date.
try this one:
<?php
$todaydate = date(d-m-Y,strtotime($_GET['date']));
$today = date("d-m-Y");
$older= date("d-m-Y",strtotime("-15 day"));
if (strtotime($todaydate) <= strtotime($older))
{
$todaydate= $today;
}
?>
$previousDate = "2012-09-30";
if (strtotime($previousDate) <= strtotime("-15 days")) {
//the date in $previousDate is earlier or is equal to the date 15 days before from today
}
Related
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) {
}
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);
}
I'm using the following code to see if a date falls between 2 other dates.
public function dateCompare($date1, $date2)
{
$interimDate = date('d/m/Y');
$StartDate = DateTime::createFromFormat('d/m/Y', $date1);
$EndDate = DateTime::createFromFormat('d/m/Y', $date2);
if ($interimDate > $StartDate && $interimDate < $EndDate)
{
echo 'Falls during given period';
}
else {
echo 'Does not fall during given period';
}
The two dates passed as follows
dateCompare('01/08/14', '30/12/14');
For some reason I continually get the message that todays date does not fall between the given period. I have checked the servers datetime and it is correct. Is anyone able to point out what exactly is causing the error?
You have a 2 letter years, so it should be lower case y for your format: d/m/y.
Also, make $interimDate equal to a new DateTime() object so you can compare properly.
I'm trying to use DateTime to check if a credit card expiry date has expired but I'm a bit lost.
I only want to compare the mm/yy date.
Here is my code so far
$expmonth = $_POST['expMonth']; //e.g 08
$expyear = $_POST['expYear']; //e.g 15
$rawExpiry = $expmonth . $expyear;
$expiryDateTime = \DateTime::createFromFormat('my', $rawExpiry);
$expiryDate = $expiryDateTime->format('m y');
$currentDateTime = new \DateTime();
$currentDate = $currentDateTime->format('m y');
if ($expiryDate < $currentDate) {
echo 'Expired';
} else {
echo 'Valid';
}
I feel i'm almost there but the if statement is producing incorrect results. Any help would be appreciated.
It's simpler than you think. The format of the datess you are working with is not important as PHP does the comparison internally.
$expires = \DateTime::createFromFormat('my', $_POST['expMonth'].$_POST['expYear']);
$now = new \DateTime();
if ($expires < $now) {
// expired
}
You can use the DateTime class to generate a DateTime object matching the format of your given date string using the DateTime::createFromFormat() constructor.
The format ('my') would match any date string with the string pattern 'mmyy', e.g. '0620'. Or for dates with 4 digit years use the format 'mY' which will match dates with the following string pattern 'mmyyyy', e.g. '062020'. It's also sensible to specify the timezone using the DateTimeZone class.
$expiryMonth = 06;
$expiryYear = 20;
$timezone = new DateTimeZone('Europe/London');
$expiryTime = \DateTime::createFromFormat('my', $expiryMonth.$expiryYear, $timezone);
See the DateTime::createFromFormat page for more formats.
However - for credit/debit card expiry dates you will also need to take into account the full expiry DATE and TIME - not just the month and year.
DateTime::createFromFormat will by default use todays day of the month (e.g. 17) if it is not specified. This means that a credit card could appear expired when it still has several days to go. If a card expires 06/20 (i.e. June 2020) then it actually stops working at 00:00:00 on 1st July 2020. The modify method fixes this. E.g.
$expiryTime = \DateTime::createFromFormat('my', $expiryMonth.$expiryYear, $timezone)->modify('+1 month first day of midnight');
The string '+1 month first day of midnight' does three things.
'+1 month' - add one month.
'first day of' - switch to the first day of the month
'midnight' - change the time to 00:00:00
The modify method is really useful for many date manipulations!
So to answer the op, this is what you need — with a slight adjustment to format to cater for single digit months:
$expiryMonth = 6;
$expiryYear = 20;
$timezone = new DateTimeZone('Europe/London');
$expiryTime = \DateTime::createFromFormat(
'm-y',
$expiryMonth.'-'.$expiryYear,
$timezone
)->modify('+1 month first day of midnight');
$currentTime = new \DateTime('now', $timezone);
if ($expiryTime < $currentTime) {
// Card has expired.
}
An addition to the above answers.
Be aware that by default the days will also be in the calculation.
For example today is 2019-10-31 and if you run this:
\DateTime::createFromFormat('Ym', '202111');
It will output 2021-12-01, because day 31 does not exist in November and it will add 1 extra day to your DateTime object with a side effect that you will be in the month December instead of the expected November.
My suggestion is always use the day in your code.
For op's question:
$y=15;
$m=05;
if(strtotime( substr(date('Y'), 0, 2)."{$y}-{$m}" ) < strtotime( date("Y-m") ))
{
echo 'card is expired';
}
For others with full year:
$y=2015;
$m=5;
if(strtotime("{$y}-{$m}") < strtotime( date("Y-m") ))
{
echo 'card is expired';
}
Would it not be simpler to just compare the string "201709" to the current year-month? Creating datetime objects will cost php some effort, I suppose.
if($_POST['expYear']. str_pad($_POST['expMonth'],2,'0', STR_PAD_LEFT ) < date('Ym')) {
echo 'expired';
}
edited as Adam states
The best answer is provided by John Conde above. It it does the minimum amount of processing: creates two correct DateTime objects, compares them and that's all it needs.
It could work also as you started but you must format the dates in a way that puts the year first.
Think a bit about it: as dates, 08/15 (August 2015) is after 12/14 (December 2014) but as strings, '08 15' is before '12 14'.
When the year is in front, even as strings the years are compared first and then, only when the years are equal the months are compared:
$expiryDate = $expiryDateTime->format('y m');
$currentDate = $currentDateTime->format('y m');
if ($expiryDate < $currentDate) {
echo 'Expired';
} else {
echo 'Valid';
}
Keep it simple, as the answer above me says except you need to string pad to the left:
isCardExpired($month, $year)
{
$expires = $year.str_pad($month, 2, '0', STR_PAD_LEFT);
$now = date('Ym');
return $expires < $now;
}
No need to add extra PHP load using DateTime
If you are using Carbon, which is a very popular Datetime extension library. Then this should be:
$expMonth = $_POST['month'];
$expYear = $_POST['year'];
$format_m_y = str_pad($expMonth,2,'0', STR_PAD_LEFT).'-'.substr($expYear, 2);
$date = \Carbon\Carbon::createFromFormat('m-y', $format_m_y)
->endOfMonth()
->startOfDay();
if ($date->isPast()) {
// this card is expired
}
Also take into consideration the exact date and time expiration:
Credit cards expire at the end of the month printed as its expiration date, not at the beginning. Many cards actually technically expire one day after the end of that month. In any case, unless they list a specific day of expiration along with month and year, they should work all the way through the end of their expiration month. Cardholders should not wait until the last moment to secure a replacement card. Source
I am getting a date back from a mysql query in the format YYYY-MM-DD.
I need to determine if that is more than three months in the past from the current month.
I currently have this code:
$passwordResetDate = $row['passwordReset'];
$today = date('Y-m-d');
$splitCurrentDate = explode('-',$today);
$currentMonth = $splitCurrentDate[1];
$splitResetDate = explode('-', $passwordResetDate);
$resetMonth = $splitResetDate[1];
$diferenceInMonths = $splitCurrentDate[1] - $splitResetDate[1];
if ($diferenceInMonths > 3) {
$log->lwrite('Need to reset password');
}
The problem with this is that, if the current month is in January, for instance, giving a month value of 01, and $resetMonth is November, giving a month value of 11, then $differenceInMonths will be -10, which won't pass the if() statement.
How do I fix this to allow for months in the previous year(s)?
Or is there a better way to do this entire routine?
Use strtotime(), like so:
$today = time(); //todays date
$twoMonthsLater = strtotime("+3 months", $today); //3 months later
Now, you can easily compare them and determine.
I’d use PHP’s built-in DateTime and DateInterval classes for this.
<?php
// create a DateTime representation of your start date
// where $date is date in database
$resetDate = new DateTime($date);
// create a DateIntveral representation of 3 months
$passwordExpiry = new DateInterval('3M');
// add DateInterval to DateTime
$resetDate->add($passwordExpiry);
// compare $resetDate to today’s date
$difference = $resetDate->diff(new DateTime());
if ($difference->m > 3) {
// date is more than three months apart
}
I would do the date comparison in your SQL expression.
Otherwise, PHP has a host of functions that allow easy manipulation of date strings:
PHP: Date/Time Functions - Manual