I would like to show "posted Today at" if the posted was posted today, and I know how to do that, but I would like it to show the default date and time format as of 12:01am, obviously because ita no longer posted "today", is there a way I can do this? Thanks for the help.
Thanks, I'll try that, here is what i have.
if($params['time'] > (time() - (60*60*24))){
$old_time = $params['time'];
$hm = date("g:ia", $old_time);
$today = elgg_echo('friendly_time_today', array($hm));
return $today;
return $today;
} else if($params['time'] > (time() - (60*60*48))){
$old_time = $params['time'];
$hm = date("g:ia", $old_time);
$yesturday = elgg_echo('friendly_time_yesturday', array($hm));
return $yesturday;
return $yesturday; }
Do you mean like this:
<?php
$sSaved = "11:08am 01.01.2012"; // comes from date("H:ia d.m.Y");
$aSaved = explode(" ", $sSaved);
if ($aSaved[1] != date("d.m.Y")) {
echo $sSaved;
} else {
echo "today";
}
If I understand your post correctly, this might make sense somehow:
# example function
function stylePostDateExample (DateTime $postDate) {
# get current date
$currDate = date_create(date('Y-m-d H:i:s'));
# grab the interval between the post date and current date
$intervalObj = date_diff($postDate, $currDate);
# simple output start
$stringOut = "Posted ";
# interpret difference
if ($intervalObj->format('%d') < 1 && $intervalObj->format('%y%m') == 0){
# still within the day
$stringOut .= "today at " . $intervalObj->format('%H:%I');
} else {
# the post date day has passed
$stringOut .= "on " . date_format($postDate, 'Y-m-d H:i:s');
}
return $stringOut;
}
# test: any previous day
$postDate = date_create('2012-01-01 00:00:00');
echo stylePostDateExample ($postDate);
# results
# -----------------------------------------
# Posted on <date value here>
# test: today
$postDate = date_create(date('Y-m-d'));
echo stylePostDateExample ($postDate);
# results
# -----------------------------------------
# Posted today at <time value here>
The function requires a datetime value which I suppose you get from the database (for the post's date of creation/posting) and it outputs a string as presented.
If I'm missing the point, please let me know.
Related
I need to compare a datetime field called "last_power" to a specific range time that starts at 7AM every day.
For example:
Day starts at 7AM.
NOW() = 2022/12/15 02:40:40 PM || last_power is setting to 2022/12/14 06:40:40 PM -> true
NOW() = 2022/12/15 02:40:40 PM || last_power is setting to 2022/12/15 11:40:40 AM -> false
I'm stucked when "last_power" is between midnight and 6:59 AM.
NOW() = 2022/12/15 12:40:40 AM || last_power is setting to 2022/12/14 01:40:40 AM -> SHOULD BE true because in my code "2022/12/15 12:40:40 AM" is < 7AM of today, but the result give me a false result.
//set
$current = time();
$new_day = strtotime('today 7:00');
$date_power = strtotime($last_power);
if ($current - $date_power >= (24 * 60 * 60) ||
($date_power < $new_day && $current >= $new_day))
{
echo "true";
//last_result < today 7:00AM -> you award your price
} else {
echo "false";
//last_result > today 7:00AM -> you have already received the price for today
}
The trick is to determine the correct cutoff time or correct date for the cutoff. This is much easier with the DateTime object.
$last_power = 'yesterday 7:00:01';
$current = new DateTime('today 6:59:59'); // demo, for production use: new DateTime('now')
$new_day = new DateTime('today 7:00'); // can be past or future
$date_power = new DateTime($last_power); // you may need to use: (new DateTime())->createFromFormat()
if($current < $new_day){ // prior to 7am
$new_day->modify('-1day'); // adjust the cutoff date
}
// now a simple comparison
if($date_power < $new_day){
echo "true, price is older than " .$new_day->format('Y-m-d, H:i:s');
}else{
echo "false, price is same age or newer than " .$new_day->format('Y-m-d, H:i:s');
}
The above will output the following (today being 2022-12-16):
false, price is newer than 2022-12-15, 07:00:00
Run it live here.
using the DateTime builtin class makes life quite easy here
$power_date = '12/16/2022 02:40:40 PM';
$power_d = (new DateTime())->createFromFormat('m/d/Y H:i:s a', $power_date);
echo 'power_date = ' . $power_d->format('d/m/Y H:i:s');
echo PHP_EOL;
$valid_end = new DateTime('today 07:00:00');
echo 'Valid End Date time = ' . $valid_end->format('d/m/Y H:i:s');
echo PHP_EOL;
$valid_start = new DateTime('yesterday 07:00:00');
echo 'Valid Start Date time = ' . $valid_start->format('d/m/Y H:i:s');
echo PHP_EOL;
if ( $power_d > $valid_start && $power_d < $valid_end) {
echo 'VALID';
} else {
echo 'INVALID';
}
i have the following code :
$now = date('2018-12-28 23:00:00');
$begintime = new DateTime('22:00');
$endtime = new DateTime('03:00');
if($now >= $endtime && $now <= $begintime){
// not between times
echo "Run";
} else {
// between times
echo "Skip";
}
and the echo is
Skip
because $now is bigger than $begintime that make the output is false
what is the correct way to know if time is not the between the $begintime and $endtime?
I searched all of the relevant issues and I've just wasted 3 days of my life because of this issues, but couldn't find something that even elucidated anything from this forum and google for me. Please help me this issue has already taken an absurd amount of days from my life already and sorry for my english before.. :D
Your code displays enormous amount of misunderstanding of how things are working and it leads to the problem. Please take a look at official documentation, you will see that date() returns string and DateTime is an object. They can't be compared directly, you need to convert them into comparable types beforehand. Also notice that DateTime expects to get a date, not just time. Actually without date being defined your $endtime is actually smaller then $starttime:
$begintime = new DateTime('22:00');
$endtime = new DateTime('03:00');
echo $begintime < $endtime ? 'Yes':'No';
This code snippet will return No.
You need to convert $now to a DateTime and you need to add dates to your start / end time marks. For example:
$now = \DateTime::createFromFormat('Y-m-d H:i:s', '2018-12-28 23:00:00', new \DateTimeZone('UTC'));
I can't provide example of converting start / end time marks because you have not defined how do they actually need to look like.
One solution may be :
$now = "23:00"; // date ('H:i');
$begintime = "22:00";
$endtime = "03:00";
$now_t = DateTime::createFromFormat('H:i', $now);
$begintime_t = DateTime::createFromFormat('H:i', $begintime);
$endtime_t = DateTime::createFromFormat('H:i', $endtime);
if ($now_t > $begintime_t || $now_t < $endtime_t)
{
echo "Skip";
}
else
{
echo "Run";
}
UPDATE
finnaly, i solve my problem..
can someone remove the duplicate tags from my question and find the correct title for this issue? maybe someone who have same issue like me, can search my question and find the answer..
sorry for my english, i still learning..
// this is variable from mysql database
$mysql_start = "2018-12-28 21:45:00"; // its from mysql DATETIME and time show when this script will be run
$begintime = "22:00"; // user can choose when this script stop
$endtime = "20:00"; // user can choose when this script run
$mysql_start = explode(' ', $mysql_start);
$taskdays = $mysql_start[0]; // 2018-12-28
echo $taskhours = $mysql_start[1]; // 21:45:00
echo "<br>";
$taskhours = explode(':',$taskhours);
$taskhours = $taskhours[0]; // 22
echo $begintime = date($begintime);
echo "<br>";
$begintime = explode(':',$begintime);
$begintime = $begintime[0]; // 20
echo "<br>";
echo $endtime = date($endtime);
echo "<br>";
$endtime = explode(':',$endtime);
$endtime = $endtime[0] - 1; // because if endtime is 6, so if its 05:59, the endtime will be end on 05
echo $endtime = str_pad($endtime, 2, '0', STR_PAD_LEFT); // if 6, it will add 0 so it will be 06
echo "<br>";
$jamarray = array("00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23");
$ray = array();
if ($begintime > $endtime){
echo '$begintime is bigger than $endtime<br>';
foreach($jamarray as $ray) {
if($ray >= $begintime or $ray <= $endtime){
//echo '<br>';
//print_r($ray);
$eray[] = $ray;
}
}
$aslinya = array_diff($jamarray,$eray);
print_r($aslinya);
if (in_array($taskhours, $aslinya))
{
echo " <= script run in this time";
}
}else{
echo '$begintime is less than $endtime<br>';
foreach($jamarray as $ray) {
if($ray >= $begintime and $ray <= $endtime){
//echo '<br>';
//print_r($ray);
$eray[] = $ray;
}
}
$aslinya = array_diff($jamarray,$eray);
print_r($aslinya);
if (in_array($taskhours, $aslinya))
{
echo " <= script run in this time";
}
}
how to understand if one date in php is less than another minus one day? I mean if for example a date is set to "2018/07/03"; how can I understand if a given date is less than "2018/07/02"
date1 : year1/month1/day1
date2: year2/month2/day2
<?php
if ($year1 >= $year2) {
if ($month1 >= $month2) {
if (($day1 - 1) > $day2) {
echo 'you could do something..';
}
}
}
?>
the above code fails if forexample $year2 = 2017 and $month2 = 11.. can anybody help me? thanks a lot..
Here, this should work.
$date_to_check = new DateTime($yesterday);
$today = new DateTime();
$time_diff = $today->diff($date_to_check)->d;
if($time_diff > 1) {
echo "This is greater than one day.";
}else{
echo "This is not greater than one day.";
$date = strtotime("2018/07/01");
$date2 = strtotime("2018/07/02");
if($date > $date2){
print('date is bigger');
// do stuff when date is bigger than date2
} else {
// else ...
print('date2 is bigger');
}
To convert string to date php has function named strtotime().
Compairing date objects is simple.
There is full information about strtotime()
http://php.net/manual/ru/function.strtotime.php
Another way:
$date = new DateTime("2018/07/01");
$date2 = new DateTime("2018/07/02");
if($date->modify("+1day") > $date2){
print('date is bigger');
// do stuff when date is bigger than date2
} else {
// else ...
print('date2 is bigger or equal');
}
Notice modify modifies $date object itself.
Read more here http://php.net/manual/en/class.datetime.php
This is setup to show a button between 2 dates set. And to show a "Sign up starts at xxx" before the set start up date, and "Sign up closed the xxxx" after the set end date...
Somehow nothing shows for the "active periode" / the dates in betweeen...
$DateToday = date('Ymd');
$DateStart = get_field('pamelding_fra');
$DateEnd = get_field('pamelding_slutt');
$DateStartOut = new DateTime($DateStart);
$DateEndOut = new DateTime($DateEnd);
if ($DateStart >= $DateToday){
$ClassStatus = "<div class=\"OpenClassButton\"><span class=\"ClassFullWarning\">Påmeldingen åpner " . $DateStartOut->format('j M Y') . "</span></div>";
$ClassButton = $ClassStatus;
}elseif ($DateEnd <= $DateToday){
$ClassStatus = "<div class=\"OpenClassButton\"><span class=\"ClassFullWarning\">Påmeldingen stengte " . $DateEndOut->format('j M Y') . "</span></div>";
$ClassButton = $ClassStatus;
}elseif ($DateStart <= $DateToday && $DateEnd >= $DateToday){
//Do some stuff - show button, this is the active time.
}
Might not be best-practice and I might make stuff difficult for me, suggestions appriciated.
Don't compare dates using date strings. If they are in different formats (like Ymd, mdY etc) you will get unwanted results. Use unix timestamps instead.
$today = time(); // Get today's timestamp
if ($today < strtotime($DateStart)) {
// Do stuff before
} elseif ($today > strtotime($DateEnd)) {
// Do stuff after
} else {
// Active. No need for any conditions here,
// since we only have three states.
}
Does anyone have a PHP snippet to calculate the next business day for a given date?
How does, for example, YYYY-MM-DD need to be converted to find out the next business day?
Example:
For 03.04.2011 (DD-MM-YYYY) the next business day is 04.04.2011.
For 08.04.2011 the next business day is 11.04.2011.
This is the variable containing the date I need to know the next business day for
$cubeTime['time'];
Variable contains: 2011-04-01
result of the snippet should be: 2011-04-04
Next Weekday
This finds the next weekday from a specific date (not including Saturday or Sunday):
echo date('Y-m-d', strtotime('2011-04-05 +1 Weekday'));
You could also do it with a date variable of course:
$myDate = '2011-04-05';
echo date('Y-m-d', strtotime($myDate . ' +1 Weekday'));
UPDATE: Or, if you have access to PHP's DateTime class (very likely):
$date = new DateTime('2018-01-27');
$date->modify('+7 weekday');
echo $date->format('Y-m-d');
Want to Skip Holidays?:
Although the original poster mentioned "I don't need to consider holidays", if you DO happen to want to ignore holidays, just remember - "Holidays" is just an array of whatever dates you don't want to include and differs by country, region, company, person...etc.
Simply put the above code into a function that excludes/loops past the dates you don't want included. Something like this:
$tmpDate = '2015-06-22';
$holidays = ['2015-07-04', '2015-10-31', '2015-12-25'];
$i = 1;
$nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
while (in_array($nextBusinessDay, $holidays)) {
$i++;
$nextBusinessDay = date('Y-m-d', strtotime($tmpDate . ' +' . $i . ' Weekday'));
}
I'm sure the above code can be simplified or shortened if you want. I tried to write it in an easy-to-understand way.
For UK holidays you can use
https://www.gov.uk/bank-holidays#england-and-wales
The ICS format data is easy to parse. My suggestion is...
# $date must be in YYYY-MM-DD format
# You can pass in either an array of holidays in YYYYMMDD format
# OR a URL for a .ics file containing holidays
# this defaults to the UK government holiday data for England and Wales
function addBusinessDays($date,$numDays=1,$holidays='') {
if ($holidays==='') $holidays = 'https://www.gov.uk/bank-holidays/england-and-wales.ics';
if (!is_array($holidays)) {
$ch = curl_init($holidays);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$ics = curl_exec($ch);
curl_close($ch);
$ics = explode("\n",$ics);
$ics = preg_grep('/^DTSTART;/',$ics);
$holidays = preg_replace('/^DTSTART;VALUE=DATE:(\\d{4})(\\d{2})(\\d{2}).*/s','$1-$2-$3',$ics);
}
$addDay = 0;
while ($numDays--) {
while (true) {
$addDay++;
$newDate = date('Y-m-d', strtotime("$date +$addDay Days"));
$newDayOfWeek = date('w', strtotime($newDate));
if ( $newDayOfWeek>0 && $newDayOfWeek<6 && !in_array($newDate,$holidays)) break;
}
}
return $newDate;
}
function next_business_day($date) {
$add_day = 0;
do {
$add_day++;
$new_date = date('Y-m-d', strtotime("$date +$add_day Days"));
$new_day_of_week = date('w', strtotime($new_date));
} while($new_day_of_week == 6 || $new_day_of_week == 0);
return $new_date;
}
This function should ignore weekends (6 = Saturday and 0 = Sunday).
This function will calculate the business day in the future or past. Arguments are number of days, forward (1) or backwards(0), and a date. If no date is supplied todays date will be used:
// returned $date Y/m/d
function work_days_from_date($days, $forward, $date=NULL)
{
if(!$date)
{
$date = date('Y-m-d'); // if no date given, use todays date
}
while ($days != 0)
{
$forward == 1 ? $day = strtotime($date.' +1 day') : $day = strtotime($date.' -1 day');
$date = date('Y-m-d',$day);
if( date('N', strtotime($date)) <= 5) // if it's a weekday
{
$days--;
}
}
return $date;
}
What you need to do is:
Convert the provided date into a timestamp.
Use this along with the or w or N formatters for PHP's date command to tell you what day of the week it is.
If it isn't a "business day", you can then increment the timestamp by a day (86400 seconds) and check again until you hit a business day.
N.B.: For this is really work, you'd also need to exclude any bank or public holidays, etc.
I stumbled apon this thread when I was working on a Danish website where I needed to code a "Next day delivery" PHP script.
Here is what I came up with (This will display the name of the next working day in Danish, and the next working + 1 if current time is more than a given limit)
$day["Mon"] = "Mandag";
$day["Tue"] = "Tirsdag";
$day["Wed"] = "Onsdag";
$day["Thu"] = "Torsdag";
$day["Fri"] = "Fredag";
$day["Sat"] = "Lørdag";
$day["Sun"] = "Søndag";
date_default_timezone_set('Europe/Copenhagen');
$date = date('l');
$checkTime = '1400';
$date2 = date(strtotime($date.' +1 Weekday'));
if( date( 'Hi' ) >= $checkTime) {
$date2 = date(strtotime($date.' +2 Weekday'));
}
if (date('l') == 'Saturday'){
$date2 = date(strtotime($date.' +2 Weekday'));
}
if (date('l') == 'Sunday') {
$date2 = date(strtotime($date.' +2 Weekday'));
}
echo '<p>Næste levering: <span>'.$day[date("D", $date2)].'</span></p>';
As you can see in the sample code $checkTime is where I set the time limit which determines if the next day delivery will be +1 working day or +2 working days.
'1400' = 14:00 hours
I know that the if statements can be made more compressed, but I show my code for people to easily understand the way it works.
I hope someone out there can use this little snippet.
Here is the best way to get business days (Mon-Fri) in PHP.
function days()
{
$week=array();
$weekday=["Monday","Tuesday","Wednesday","Thursday","Friday"];
foreach ($weekday as $key => $value)
{
$sort=$value." this week";
$day=date('D', strtotime($sort));
$date=date('d', strtotime($sort));
$year=date('Y-m-d', strtotime($sort));
$weeks['day']= $day;
$weeks['date']= $date;
$weeks['year']= $year;
$week[]=$weeks;
}
return $week;
}
Hope this will help you guys.
Thanks,.
See the example below:
$startDate = new DateTime( '2013-04-01' ); //intialize start date
$endDate = new DateTime( '2013-04-30' ); //initialize end date
$holiday = array('2013-04-11','2013-04-25'); //this is assumed list of holiday
$interval = new DateInterval('P1D'); // set the interval as 1 day
$daterange = new DatePeriod($startDate, $interval ,$endDate);
foreach($daterange as $date){
if($date->format("N") <6 AND !in_array($date->format("Y-m-d"),$holiday))
$result[] = $date->format("Y-m-d");
}
echo "<pre>";print_r($result);
For more info: http://goo.gl/YOsfPX
You could do something like this.
/**
* #param string $date
* #param DateTimeZone|null|null $DateTimeZone
* #return \NavigableDate\NavigableDateInterface
*/
function getNextBusinessDay(string $date, ? DateTimeZone $DateTimeZone = null):\NavigableDate\NavigableDateInterface
{
$Date = \NavigableDate\NavigableDateFacade::create($date, $DateTimeZone);
$NextDay = $Date->nextDay();
while(true)
{
$nextDayIndexInTheWeek = (int) $NextDay->format('N');
// check if the day is between Monday and Friday. In DateTime class php, Monday is 1 and Friday is 5
if ($nextDayIndexInTheWeek >= 1 && $nextDayIndexInTheWeek <= 5)
{
break;
}
$NextDay = $NextDay->nextDay();
}
return $NextDay;
}
$date = '2017-02-24';
$NextBussinessDay = getNextBusinessDay($date);
var_dump($NextBussinessDay->format('Y-m-d'));
Output:
string(10) "2017-02-27"
\NavigableDate\NavigableDateFacade::create($date, $DateTimeZone), is provided by php library available at https://packagist.org/packages/ishworkh/navigable-date. You need to first include this library in your project with composer or direct download.
I used below methods in PHP, strtotime() does not work specially in leap year February month.
public static function nextWorkingDay($date, $addDays = 1)
{
if (strlen(trim($date)) <= 10) {
$date = trim($date)." 09:00:00";
}
$date = new DateTime($date);
//Add days
$date->add(new DateInterval('P'.$addDays.'D'));
while ($date->format('N') >= 5)
{
$date->add(new DateInterval('P1D'));
}
return $date->format('Y-m-d H:i:s');
}
This solution for 5 working days (you can change if you required for 6 or 4 days working). if you want to exclude more days like holidays then just check another condition in while loop.
//
while ($date->format('N') >= 5 && !in_array($date->format('Y-m-d'), self::holidayArray()))