A friend of mine gave me this code, but I can't seem to get it to work. It keeps telling me that I have an undefined variable, but I have tried to define it several different ways, but it doesn't show their right age, it shows everyone as 43. Here is the code I'm using:
$bdate= getdate('$_GET["bd"]');
if($bdate == 0){ $nodate = 1; }
$bdate = strtotime( $bdate );
$birthday = date("n/j/Y",$bdate); //must be as m/d/yyyy
$bday = explode("/", $birthday); //parse
$b_mm = $bday[0]; //birthday month
$b_dd = $bday[1]; //birthday day
$b_yyyy = $bday[2]; //birthday year
//compare timestamps of mm/dd for birthday and today
$bday_mm_dd = mktime(0,0,0,$b_mm,$b_dd,0);
$today_mm_dd = mktime(0,0,0,date("m"),date("d"),0);
$age = date("Y", time()) - $b_yyyy;
if ($bday_mm_dd > $today_mm_dd) {
//birthday hasnt happened yet this year
$age = $age - 1;
}
Just for clarification in my sql statement I have the birthdate listed as bd.
If anyone can help, I would greatly appreciate it.
getdate() returns an associative array, not a textual representation of a date. strtotime() can't make sense of this, and your first call to date() then interprets its timestamp argument as zero, the UNIX epoch.
Guess how many years ago the epoch was? :)
Skip strtotime() and just pass $bdate[0] to date(). That will contain the epoch timestamp representation of 'bd'.
Related
this code keeps telling me that $lasUpdate is always greater than $yesterday no matter the change i make to $yesterday result is (12/31/14 is greater than 01/19/15 no update needed). i feel like i'm missing something simple thank you in advance it is greatly appreciated.
$result['MAX(Date)']='12/31/14';
$lastUpdate = date('m/d/y', strtotime($result['MAX(Date)']));
$yesterday = date('m/d/y', strtotime('-1 day'));
if($lastUpdate<$yesterday){echo $lastUpdate.'is less '.$yesterday.'<br>'.'update needed';}
if($lastUpdate>=$yesterday){echo $lastUpdate.'is greater than '.$yesterday.'<br>'.'no update needed';
You have fallen victim to PHP type juggling with strings. A date function has a return value of a string. You cannot compare dates in their string format since PHP will juggle strings into integers in the context of a comparison. The only exception is if the string is a valid number. In essence, you are doing:
if ('12/31/14' < '01/19/15') { ... }
if ('12/31/14' >= '01/19/15') { ... }
Which PHP type juggles to:
if (12 < 1) { ... }
if (12 >= 1) { ... }
And returns false on the first instance, and true on the second instance.
Your solution is to not wrap date around the strtotime functions, and just use the returned timestamps from the strtotime functions themselves to compare UNIX timestamps directly:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
You will however want to use date when you do the echo back to the user so they have a meaningful date string to work with.
Try something like this:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
if ($lastUpdate < $yesterday) { /* do Something */ }
12/31/14 is greater than 01/19/15
Because 1 is greater than 0. If you want to compare dates that way you will need to store them in a different format (from most to least significant digit), for example Ymd.
Or store the timestamps you are making in the different variables and compare them.
The date to be checked is as follows :
$submission_date = 12-25-2014; //The date in mm-dd-yyyy format that is to be tested against today's date
Now I want to echo the error message since the date contained in a variable $submission_date is a future date.
How should I do this efficiently and effectively using PHP?
Thanks in advance.
Many ways to do this (use DateTime::createFromFormat() to control exact format of input dates, for example) but perhaps the simplest that suits the example is:
$isFuture = (strtotime($submission_date) > strtotime($_POST['current_date']))
Note that OP changed the question. If desired date to test against is not in $_POST array, just replace strtotime($_POST['current_date']) with time() to use current system time.
To compare against current date, disregarding time of day, use:
$today = new DateTime(date("Y-m-d"));
// $today = new DateTime("today"); // better solution courtesy of Glavić
// see http://php.net/manual/en/datetime.formats.relative.php for more info
$today_timestamp = $today->getTimestamp();
If posted format is in m-d-Y, then you cannot convert it to unix timestamp directly with strtotime() function, because it will return false.
If you need to use strtotime() then change the input format to m/d/Y by simple str_replace().
On the other hand, you could use DateTime class, where you can directly compare objects:
$submission_date = DateTime::createFromFormat('!m-d-Y', $submission_date);
$today_date = new DateTime('today');
if ($submission_date > $today_date) {
echo "submission_date is in the future\n";
}
demo
With PHP DateTime you can check whether the input date is future or old w.r.to the todate.
$submission_date = DateTime::createFromFormat('m-d-Y', $submission_date);
$submission_date = $submission_date->format('Y-m-d');
$current_date = new DateTime('today');
$current_date = $current_date->format('Y-m-d');
if ($submission_date > $current_date)
{
echo "Future date";
}
else
{
echo "Old date";
}
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
I have data coming from the database in a 2 digit year format 13 I am looking to convert this to 2013 I tried the following code below...
$result = '13';
$year = date("Y", strtotime($result));
But it returned 1969
How can I fix this?
$dt = DateTime::createFromFormat('y', '13');
echo $dt->format('Y'); // output: 2013
69 will result in 2069. 70 will result in 1970. If you're ok with such a rule then leave as is, otherwise, prepend your own century data according to your own rule.
One important piece of information you haven't included is: how do you think a 2-digit year should be converted to a 4-digit year?
For example, I'm guessing you believe 01/01/13 is in 2013. What about 01/01/23? Is that 2023? Or 1923? Or even 1623?
Most implementations will choose a 100-year period and assume the 2-digits refer to a year within that period.
Simplest example: year is in range 2000-2099.
// $shortyear is guaranteed to be in range 00-99
$year = 2000 + $shortyear;
What if we want a different range?
$baseyear = 1963; // range is 1963-2062
// this is, of course, years of Doctor Who!
$shortyear = 81;
$year = 100 + $baseyear + ($shortyear - $baseyear) % 100;
Try it out. This uses the modulo function (the bit with %) to calculate the offset from your base year.
$result = '13';
$year = '20'.$result;
if($year > date('Y')) {
$year = $year - 100;
}
//80 will be changed to 1980
//12 -> 2012
Use the DateTime class, especially DateTime::createFromFormat(), for this:
$result = '13';
// parsing the year as year in YY format
$dt = DateTime::createFromFormat('y', $result);
// echo it in YYYY format
echo $dt->format('Y');
The issue is with strtotime. Try the same thing with strtotime("now").
Simply prepend (add to the front) the string "20" manually:
$result = '13';
$year = "20".$result;
echo $year; //returns 2013
This might be dumbest, but a quick fix would be:
$result = '13';
$result = '1/1/20' . $result;
$year = date("Y", strtotime($result)); // Returns 2013
Or you can use something like this:
date_create_from_format('y', $result);
You can create a date object given a format with date_create_from_format()
http://www.php.net/manual/en/datetime.createfromformat.php
$year = date_create_from_format('y', $result);
echo $year->format('Y')
I'm just a newbie hack and I know this code is quite long. I stumbled across your question when I was looking for a solution to my problem. I'm entering data into an HTML form (too lazy to type the 4 digit year) and then writing to a DB and I (for reasons I won't bore you with) want to store the date in a 4 digit year format. Just the reverse of your issue.
The form returns $date (I know I shouldn't use that word but I did) as 01/01/01. I determine the current year ($yn) and compare it. No matter what year entered is if the date is this century it will become 20XX. But if it's less than 100 (this century) like 89 it will come out 1989. And it will continue to work in the future as the year changes. Always good for 100 years. Hope this helps you.
// break $date into two strings
$datebegin = substr($date, 0,6);
$dateend = substr($date, 6,2);
// get last two digits of current year
$yn=date("y");
// determine century
if ($dateend > $yn && $dateend < 100)
{
$year2=19;
}
elseif ($dateend <= $yn)
{
$year2=20;
}
// bring both strings back into one
$date = $datebegin . $year2 . $dateend;
I had similar issues importing excel (CSV) DOB fields, with antiquated n.american style date format with 2 digit year. I needed to write proper yyyy-mm-dd to the db. while not perfect, this is what I did:
//$col contains the old date stamp with 2 digit year such as 2/10/66 or 5/18/00
$yr = \DateTime::createFromFormat('m/d/y', $col)->format('Y');
if ($yr > date('Y')) $yr = $yr - 100;
$md = \DateTime::createFromFormat('m/d/y', $col)->format('m-d');
$col = $yr . "-" . $md;
//$col now contains a new date stamp, 1966-2-10, or 2000-5-18 resp.
If you are certain the year is always 20 something then the first answer works, otherwise, there is really no way to do what is being asked period. You have no idea if the year is past, current or future century.
Granted, there is not enough information in the question to determine if these dates are always <= now, but even then, you would not know if 01 was 1901 or 2001. Its just not possible.
None of us will live past 2099, so you can effectively use this piece of code for 77 years.
This will print 19-10-2022 instead of 19-10-22.
$date1 = date('d-m-20y h:i:s');
I have an array which will output a date. This date is outputted in the mm/dd/yyyy format. I have no control over how this outputted so I cant change this.
Array
(
[date] => 04/06/1989
)
I want to use php to check if this date matches the current date (today), but ignoring the year. So in the above example I just want to check if today is the 6th April. I am just struggling to find anything which documents how to ignore the years.
if( substr( $date, 0, 5 ) == date( 'm/d' ) ) { ...
Works only if it's certain that the month and date are both two characters long.
Came in a little late, but here’s one that doesn’t care what format the other date is in (e.g. “Sep 26, 1989”). It could come in handy should the format change.
if (date('m/d') === date('m/d', strtotime($date))) {
echo 'same as today';
} else {
echo 'not same as today';
}
this will retrieve the date in the same format:
$today = date('m/d');
Use this:
$my_date = YOUR_ARRAY[date];
$my_date_string = explode('/', $my_date);
$curr_date = date('m,d,o');
$curr_date_string = explode(',', $date);
if (($my_date_string[0] == $curr_date_string[0]) && ($my_date_string[1] == $curr_date_string[1]))
{
DO IT
}
This way, you convert the dates into strings (day, month, year) which are saved in an array. Then you can easily compare the first two elements of each array which contains the day and month.
You can use for compare duple conversion if you have a date.
$currentDate = strtotime(date('m/d',time())); --> returns current date without care for year.
//$someDateTime - variable pointing to some date some years ago, like birthday.
$someDateTimeUNIX = strtotime($someDateTime) --> converts to unix time format.
now we convert this timeunix to a date with only showing the day and month:
$dateConversionWithoutYear = date('m/d',$someDateTimeUNIX );
$dateWithoutRegardForYear = strtotime($dateConversionWithoutYear); -->voila!, we can now compare with current year values.
for example: $dateWithoutRegardForYear == $currentDate , direct comparison
You can convert the other date into its timestamp equivalent, and then use date() formatting to compare. Might be a better way to do this, but this will work as long as the original date is formatted sanely.
$today = date('m/Y', time());
$other_date = date('m/Y', strtotime('04/06/1989'));
if($today == $other_date) {
//date matched
}
hi you can just compare the dates like this
if(date('m/d',strtotime($array['date']])) == date('m/d',strtotime(date('Y-m-d H:i:s',time()))) )