Formatting a date with uncertain data - php

A quick search didn't return any results that seemed to fit what I was looking for so I come here asking for your help.
I am working on formatting a birthday. The problem is, the use has the ability to enter only some (or none) of the data. It is stored separately as day, month, and year.
Basically, based on the data present will determine how the date will be formatted and displayed back to the user.
My approach is:
#prepare birthday
$bday = new DateTime();
$bday->setTimezone(new DateTimeZone('America/New_York'));
$bday->setDate($row->birth_year,$row->birth_month,$row->birth_day);
if($row->birth_month && $row->birth_year && $row->birth_day){
//Full birthday entered
$display_bday = $bday->format('F j, Y');
} elseif($row->birth_month && !$row->birth_year && !$row->birth_day){
//Only a month
$display_bday = $bday->format('F');
} elseif($row->birth_month && $row->birth_year && !$row->birth_day){
//Only Month and year
$display_bday = $bday->format('F, Y');
}
I was wondering if there is a better way to accomplish this task. I guess I figure there has to be a better way. Thanks in advance. If I need to clarify anything please just ask!
edit: removed unnecessary code

Your code could output invalid date since you are not filtering input when setting up a DateTime object. When the $row->birth_day equals 0, the DateTime object will move back to previous month (last date).
So, I suggest to consider that:
$display_bday = null;
if ($row->birth_month) {
if ($row->birth_year) {
if ($row->birth_day) {
// day, month, and year
$display_bday = date('F j, Y', strtotime("$row->birth_year-$row->birth_month-$row->birth_day"));
} else {
// month and year
$display_bday = date('F, Y', strtotime("$row->birth_year-$row->birth_month-01"));
}
} else {
if ($row->birth_day) {
// day and month
$display_bday = date('F j', strtotime("2016-$row->birth_month-$row->birth_day"));
} else {
// month only
$display_bday = date('F', strtotime("2016-$row->birth_month-01"));
}
}
}

Related

PHP Checking if outputted date is less than current date

I have the following function which works well but would like to check the returned date and compare with the current date if before current date to show something if current or in future show as normal.
Function:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
Call:
echo '<li class="list-group-item">Support Expires: ' . dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60 . '</li>');
Output:
2nd March 2016
So as not today's date and/or before today's date would like to echo a message, else just show the date.
In PHP it is very simple to compare two different dates using < = > like you normally compare numbers. The only step prior to this is below:
//Tell PHP that the value in variable is a date value
$date_1 = date_create("2017-05-29"); //This value can be any valid date format
date_1_formatted = date_format($date_1, "Y-m-d"); //This formats the date_1
//Now you can simply put the second date, for example, today.
$date_2 = date_create("2017-04-29"); //This value can be any valid date format
date_2_formatted = date_format($date_2, "Y-m-d"); //This formats the date_1
//For current date, it is simpler
$date_today_formatted = date("Y-m-d");
//Now you can compare these two dates easily
if ($date_1 < $date_today_formatted) {
echo "Date 1 falls before today.";
}
else {
echo "Date 1 falls after today.";
}
Hope this helps!
I managed to work it out using the following 2 functions:
function dateFormat( $old, $correction ) {
$old_date_timestamp = strtotime( $old );
$new_date = date( 'jS F Y', $old_date_timestamp + $correction );
return $new_date;
}
function checkLicenceSupport($licence_date) {
$date_now = new dateTime();
$date_set = dateFormat($licence_date, 11*60*60);
if ($date_now > $date_set) {
return 'date expired';
} else {
return 'date valied';
}
}
I have the following function which works well, but would like to
check the returned date and compare with the current date.
If it is before the current date, show something.
If it is the current date, or in future, show as normal.
I needed to rewrite your question, because lack of grammar and punctuation made it confusing. No offense intended.
Your call code has the closing parenthesis for your function call is placed wrongly.
dateFormat($purchase_data['verify-purchase']['supported_until'], 11*60*60)
It is more readable to use full days or hours (in seconds):
11*86400 //(11 Days);
11*3600 //(11 Hours);
The function and code, as you have it now, will always return a date in the future of the date you've submitted via the call. (I can't tell from your question whether this was intended or not).
Currently, there is no "comparison" in your function. But your question indicates you want to compare the submitted date to the current date and then do something in certain cases.
If you are going to use a Unix timestamp, then there's no need for multiple formatting, compare the two dates in Unix, then format the result.
function dateCompare($submittedDate){
//This is only needed if your submitted date is not a unix timestamp already
$submittedDate = strtotime($submittedDate);
$currentDate = time(); // Creates timestamp of current datetime
if($submittedDate < $currentDate) {
//show something i.e. return "Support Has Expired";
}else {
return date('jS F Y', $submittedDate);
}
}
echo '<li class="list-group-item">Support Expires: '.dateCompare($purchase_data['verify-purchase']['supported_until']).'</li>';

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

How to determine if date entered by the user is in future?

How do I know in PHP that the date entered by the user in future than the current date.
i.e
if($current_date<$future_date)
{
//do all the success actions here
}
else
{
//show the user that they have selected a date in the past.
}
Well you first need to convert the date string using strtotime() function and then check if future date value is greater than current date value.
Here is the code snippet:
$today_date=date('Y-m-d H:i:s');
$current_date=strtotime($today_date);
$future_date=strtotime($future_date);//retrieved from user's input
Now you can call your function:
if($current_date<$future_date)
{
//do all the success actions here
}
else
{
//show the user that they have selected a date in the past.
}
I suppose you know the date format in which your users enters their date cos it will help you understand what date format you will be working with. But irrespective of whatever date format you are working with, you can always convert it to a more suitable one using:
strtotime()
Below is an example of checking a future date (working strictly with date)
$currentDate = date("Y-m-d");
$userFututeDate = "2014-05-08";
if($userFututeDate > $currentDate){
echo 'You have selected a date in the future';
}
else{
echo 'You have selected a date in the past.';
}
Below is another example of checking a future date (working with date and time)
$currentDateTime = date("Y-m-d H:i:s");
$userFututeDateTime = "2014-05-07 05:05:08";
if($userFututeDateTime > $currentDateTime){
echo 'You have selected a date in the future';
}
else{
echo 'You have selected a date in the past.';
}
Perhaps, you need to understand how to play around with strtotime(), find some sample below:
$dateVar = "25-07-2014 05:05:08";
echo date("F j Y", strtotime($dateVar));
echo '<br><br>';
echo date("Y-m-d", strtotime($dateVar));
echo '<br><br>';
echo date("F jS Y, g:i a", strtotime($dateVar));
Check out for more on strtotime()

Odd Date("Y-m-d") result

Im having some bizarre results in regards to the php date() function. Basically Im getting a date from a Mysql database which is in a string format, split into three elements. This would be Day, Month, Year (15 september 2012 for example) Im ultimately comparing two dates to see if it has expired. But the issue is that only certain dates are allowing the code to work, and some do not work at all (or allow the if statement to work effectively) Below is my code, any help would be great.
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year'))) ;
if ($expire < $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
Im sure its something simple, but for some reason I cannot solve it.
You need to compare the Unix timestamps.
$today = time();
$expire = strtotime($this->getData('date_day')."-".
$this->getData('date_month')."-".$this->getData('date_year')) ;
if ($expire > $today)
{
echo 'expired';
}
else
{
echo 'Not expired';
}
It looks like strtotime is expected a US date format; you need to swap the month and the day around to generate a valid date:
$today = date("d-m-Y");
$expire = date("d-m-Y",strtotime($this->getData('date_month')."-".
$this->getData('date_day')."-".$this->getData('date_year'))) ;
On the other hand, see Stephen305's answer - it's a much better solution to your problem.

Comparing a date to current server date using PHP

I am using the following code to attempt to compare the current date with a date entry in a mySql database. It's code that I have found online and adapted as all the examples I have found hard-code the date to compare the current date with.
The trouble is even dates in the future are being marked as expired and I can't understand why this would be.
I am afraid that I am still new to PHP, so I may be making a schoolboy error!
$exp_date = KT_formatDate($row_issue_whatson1['dateToShow']);
$todays_date = date("d-m-Y");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) { echo "Not expired"; } else { echo "expired"; }
Any help would be most appreciated.
I should add that the date time format used in the database entries is dd/mm/yyyy
Instead of making a string then converting it to a timestamp, simply use mktime:
<?php
$today = mktime(
0, // hour
0, // minute
0 // seconds
);
?>
The rest of the values will be filled according to today's date. If this still gives problems, put in some echo's for the values of $exp_date and $expiration_date.
Edit
Since this solved the problem, the discrepancy you were seeing was because you were doing the opposite with date('d-m-Y'). You were asking for the current date and the time values are then filled in with the current time. The expiration date in the database is likely set at midnight. With both dates being equal, and it being say 11am now, you are comparing if (00:00:00 > 11:00:00) which fails.
$exp_date = 14/05/2011 // todays date, int
$server_date = server.date() // servers date, int
// check exp_date against server date
if ( $server > $exp_date)
{ echo "Sorry your 'service' has expired"; }
else
{ echo "Welcome 'members_name' to StackOverflow"; }
Try that. However you need the right date format, as server.date() is probably different in PHP.
If problem still persists I would check whether your dates are strings or integers or both. That could possibly be the issue.
Hope that helps.
DL.
Your function does not seem to be valid.
function KT_formatDate( $exp_date){
$exp_date = strtotime($exp_date);
$now = time();
if ($now > $exp_date)
return 'expired';
else
return ' Not expired';
}
$response = KT_formatDate($row_issue_whatson1['dateToShow']);

Categories