I have several dates, some of the past, some of the future, and I want to show only the next date in the future of this list. If there is no date in the future, I want to echo some text.
I am using ACF Date Picker inside a Repeater. First of all, I think I have to get the current date, to compare it with the others:
date_default_timezone_set('Europe/Berlin');
$date = date('Ymd', time());
I chose the Ymd format because the repeater outputs the dates the exact same way. Now I need to check somehow all subfields inside my repeater. I guess this is done using somehow like
$rows = get_field('repeater_field_name');
if($rows) {
foreach($rows as $row) {
// compare the dates, choose only the next coming date
// dates are stored in the_sub_field('repeater_date_field');
}
}
How can I get all the_sub_field('repeater_date_field') of my get_field('repeater_field_name') values? And how can I detect its row (for adding other sub fields to the same row)?
You can store your all dates in array. Then sort it in ascending order. Then take the first date from the list which is greater than today.
Please look into below code.
date_default_timezone_set('Europe/Berlin');
$date = date('Ymd', time());
$dates = array();
$rows = get_field('repeater_field_name');
if($rows) {
foreach($rows as $row) {
$dates[] = $row->date_field;
// compare the dates, choose only the next coming date
// dates are stored in the_sub_field('repeater_date_field');
}
}
sort($dates);
$final_date = "";
foreach($dates as $date_row){
if($date_row > $date){
$final_date = $date_row;
return true;
}
}
echo $final_date;
You can compare 2 date to solve this problem. For example
$date_bef = strtotime("151218"); // December 18, 2015
$date_after = strtotime("151219"); // December 19, 2015
if($date_after - $date_bef == 1)
echo "This is a next day";
If you don't want compare, you can add 1 day to existing time, example
$next_day = date("Ymd",strtotime("151220") + 60*60*24);
Related
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>';
So i fetched the date into MSSQL's datetime type field.
E.g 2014-01-23 06:54:49.647
I need a simple way to determine if the datetime corresponds a specific month in a condition in PHP
//i wanted something like this
$getthedate = odbc_exec($connection, "SELECT date FROM sometable WHERE ..somecondition..");
$datedata = odbc_result($getthedate, 'DATE');
if($datedata = /* is january */) {
//do something
}
You can convert the time to a UNIX timestamp by using strtotime:
$timestamp = strtotime($datedata); //2014-01-23 06:54:49.647 = 1390460089
Then convert the timestamp into whatever format you want with the 'date' function:
$month = date('F', $timestamp); // Outputs: January
Then you can use $month to compare in your if statement as it returns the month of the date.
if ($month == "January") {
//do something
}
If you have a variable containing the date time string
2014-01-23 06:54:49.647
and you know it'll be in that format, simply use http://php.net/substr to get the month.
(This ignores any time zone issues since you didn't mention that.)
try this
<?php
$timestamp="2014-01-23 06:54:49.647";
$month = date('F', $timestamp);
$current_month=date('F');
if($month==$current_month)
{
//do something
}
?>
OR
<?php
$timestamp="2014-01-23 06:54:49.647";
$month = date('m', $timestamp);
$current_month=date('m');
if($month==$current_month)
{
//do something
}
check this
$datedata = "2014-10-19 12:36:00";
if(strtolower(date('F',strtotime($datedata))) == strtolower(date('F'))){
echo "success";
}else{
echo "unsucess";
}
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'm making a news website for games and I want a page where you can find all the news subject. So I decided to use it like a lot of webpages do.
Example:
Now I want it like that, but i don't know how to make that like that. I've made a little beginning and I hope you guys can help me with this!
$query = mysql_query("SELECT * FROM `gb_news` order by `datetime` DESC");
while($news = mysql_fetch_array($query)) {
echo $news['title'];
echo $news['datetime'];
}
It's a really simple code, but I only want to know how I add these days when an artical has a new date in the database.
Store the date outside your loop, then display a title only when the date changes.
$date = "";
while ($news = mysql_fetch_array($query)) {
if ($news['datetime'] != $date) {
$date = $news['datetime'];
echo $date;
}
echo $news['title'];
}
Something like this may work for you:
$query = mysql_query("SELECT * FROM `gb_news` order by `datetime` DESC");
$prevDate ='';
while($news = mysql_fetch_array($query))
{
$tmpDate = DateTime::createFromFormat('Y-m-d H:i:s', $news['datetime']);
if($prevDate!=$tmpDate)
{
$prevDate = $tmpDate->format('d/m/Y');
echo '<h1>'.$prevDate.'</h1><hr />';
}
echo '<p>'.$tmpDate->format('H:i').' - '.$news['title'].'</p>';
}
This is assuming your datetime column is in the format YYYY-MM-DD hh:mm:ss and you want to display the date as DD/MM/YYYY, obviously edit to taste!
Also your PHP version must be >= 5.3.0 to use the DateTime class
Well what you can do is store the date and then change the layout each time the date changes:
while($news = mysql_fetch_array($query)) {
if(empty($date) || $date != date("format", $news['datetime'])){
$date = date("format", $news['datetime']);
//echo/print some html to show new section
}
echo $news['title'];
echo $news['datetime'];
}
This will handle the date comparisons and knowing when to change dates. "format" indicates the kind of date formatting you would like since you can echo/print the $date.
PHP date
NOTICE: Do not use MySQL_* for it has been deprecated as of PHP 5.5. Use MySQLi_* or PDO instead
I'm not sure I quite understand what you're trying to accomplish. To get your data to display like the image you included you would want to group items of the same date either in MySQL or PHP (or combination really).
Something like:
while ($news...) {
// Get this article date
$thisDate = new DateTime($news['datetime']) // Assuming this is a true datetime value
// Compare this article date with previous article date to determine if we should start a new date header
if (!empty($onDate) // We have previous articles to compare with
&& ($thisDate->format('l d F') == $onDate)) // This article date matches previous so keep in same group
{
echo $news['title'];
} else { // No existing articles or new date = new header
$onDate = $thisDate->format('l d F'); // See options: http://www.php.net/manual/en/function.date.php
echo $onDate
echo $news['title'];
}
}
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()))) )