i am trying to substract 1 day from date string, if condition is met.
If condition (if time between 12-16) works fine, but outcome of yesterday's date is wrong.
This is what i tried with research from stackoverflow:
<?php
#trying to remove 1 day from date
$date = date("d/m/y");
if (date('H') < 16 && date('H') > 12) {
$date2 = strtotime(date('d/m/y') . ' -1 day');
$date2 = date('d/m/y', $date2);
}
echo "Todays date is {$date} and yesterday was {$date2}";
?>
Outcome from phpfiddle:
Todays date is 23/10/16 and yesterday was 31/12/69
Can someone share some light on it, how it should be done ?
instead
$date2 = strtotime(date('d/m/y') . ' -1 day');
use
$date2 = strtotime('-1 day');
Related
I want to detect how to detect if the day is in the specific settings that I save.
I already save the settings
$checkday = "Sunday";
$period = "48"; // this in hours
So I need to check if today in this week is Sunday + 48 hours after (means Tuesday) then run a function.
I already make these code
$starttimer = date('Y-m-d 00:00:00', strtotime($checkday));
$endtimer = date('Y-m-d H:i:s', strtotime('+' . $period . ' hour', strtotime(date('Y-m-d 00:00:00'))));
if(time() >= strtotime($starttimer) && time() <= strtotime($endtimer)){
// this should run a function
}
This code is working if today is Sunday, but the problem is when today is Monday it will detect next Week Monday. I need it to check from this week Sunday + 48 hours after then run function.
The conclusion is I want to run the function on every week start from Sunday + 48 hours after.
Thanks for reading my problem, hope someone can help me.
I think you need get day of this week.
because if checkday = "Monday" then $starttimer will return Monday of next week.
<?php
$checkday = 'Monday';
$period = 48;
$day_this_week = "$checkday this week";
$starttimer = date('Y-m-d 00:00:00', strtotime($day_this_week));
$endtimer = date('Y-m-d H:i:s', strtotime('+' . $period . ' hour', strtotime(date('Y-m-d 00:00:00'))));
var_dump($starttimer);//string(19) "2022-09-12 00:00:00"
You can use the flexibility of strtotime to find the time of the last occurance of $checkDay. You also need to check to see that today is the check day and run in that condition as well.
<?php
$checkDay = 'Sunday';
$period = 48;
$isCheckDay = date('w', strtotime($checkDay)) === date('w');
$start = strtotime('last ' . $checkDay);
$end = strtotime(date('Y-m-d', $start) . ' +' . $period . ' hours');
$now = time();
if ($isCheckDay || ($now >= $start && $now <= $end)) {
echo 'run function';
}
It is not necessary to work with timestamps. Datetime objects can be directly compared. This makes the code easier to read.
$checkday = "Sunday";
$period = "2 Days";
$dtStart = date_create('Tomorrow')->modify('last '.$checkday);
$dtEnd = (clone $dtStart)->modify($period);
/* Use 'Now' instead of 'Today' in the following line
* if the time periods can also be fractions of days.
*/
$dtToDay = date_create('today');
if($dtToDay >= $dtStart AND $dtToDay < $dtEnd){
echo 'run function';
}
else {
echo 'do nothing';
}
$dtStart is always the last $checkday weekday before tomorrow. A time in hours can also be entered for $period, for example "48 hours".
Demo: https://3v4l.org/5d2Xt
You can use below code for fulfill your requirement...
<?php
$checkday = "Sunday";
$period = "48"; // this in hours
echo date('l', strtotime($checkday. ' + '.$period.' hours'));
?>
I'm trying make a function to return the exact date of previous months.
That is a example of my code:
// Dates in TimeStamp
$ts_now = strtotime('now');
$ts_month1 = strtotime("-1 month", $ts_now);
$ts_month2 = strtotime("-2 month", $ts_now);
$ts_month3 = strtotime("-3 month", $ts_now);
// Dates Formated
$date_now = date('Y-m-d', $ts_now);
$date_month1 = date('Y-m-d', $ts_month1);
$date_month2 = date('Y-m-d', $ts_month2);
$date_month3 = date('Y-m-d', $ts_month3);
//Output
echo $date_now; //2020-04-30
echo $date_month1; //2020-03-30
echo $date_month2; //2020-03-01
echo $date_month3; //2020-01-30
The problem is in $date_month2 that represents February, the output is 2020-03-01 instead 2020-02-29 and I suppose that problem will happen in months who have 30 days when present date have 31 days.
What is the best way to resolve that?
As you can see working with the end of the month can be problematic because of how PHP works with dates. Your best bet is to go back to the beginning of the month, do your date math (i.e. go backwards in time), and then go to the date you want. That way you can check to see if the current day is greater than the number of days in month. If so, use the last day of the month instead.
function getMonthsAgo(int $n): string {
$date = new DateTime();
$day = $date->format('j');
$date->modify('first day of this month')->modify('-' . $n . ' months');
if ($day > $date->format('t')) {
$day = $date->format('t');
}
$date->setDate($date->format('Y'), $date->format('m'), $day);
return $date->format('Y-m-d');
}
// Dates Formated
$date_now = date('Y-m-d');
$date_month1 = getMonthsAgo(1);
$date_month2 = getMonthsAgo(2);
$date_month3 = getMonthsAgo(3);
//Output
echo $date_now;
echo $date_month1;
echo $date_month2;
echo $date_month3;
Output:
2020-04-30
2020-03-30
2020-02-29
2020-01-30
I need to use PHP DateTime to get the first day of the current year. I've tried:
$year = new DateTime('first day of this year');
var_dump($year);
But this seems to be returning the first day of the current month: 2014-09-01 09:28:56
Why? How do I correctly get the first day of the current year?
Your relative date format 'first day of this year' is correct by returning the first day of the month because of the definition of first day of:
Sets the day of the first of the current month. This phrase is best
used together with a month name following it. (See PHP-doc)
To get the first day of the current year with the relative format you can use something like this:
'first day of January ' . date('Y')
Or use only text in the strtotime function:
date('Y-m-d', strtotime('first day of january this year'));
echo date('l',strtotime(date('Y-01-01')));
You can get the current date and then set day and month to 1:
$year = new DateTime();
$year->setDate($year->format('Y'), 1, 1);
Optionally, you can set the time to midnight:
$year->setTime(0, 0, 0);
If you want to get first day of current year just use this code
echo date("l", strtotime('first day of January '.date('Y') ));
Just wanted to record some nuance with the answer by lorem monkey
The suggested method might cause issues with when using time zones.
scenario: consider current system time is 2018-01-01 00:20:00 UTC and system default time zone is set to UTC.
date('Y') will give you 2018
if you are doing something like:
$startDate = new DateTime('first day of january '.date('Y'), new DateTimeZone('America/New_York'));
This will compute to 'first day of january 2018' but you actually needed the first date of your current year in America/New_York, which is still 2017.
Stop dropping the ball man, its not new year yet!
So it is better to just do
$startDate = new DateTime('first day of january', new DateTimeZone('America/New_York'));
And then do the modifications as needed by using the DateTime::modify() function.
Relative date formats are fun.
My scenario: I wanted to get the bounds of this year as in 2018-01-01 00:00:00 to 2018-12-31 23:59:59
This can be achieved in two ways with relative date formats.
one way is to use the DateTime::modify() function on the object.
$startDate = (new DateTime('now', new DateTimeZone("America/New_York")));
$endDate = (new DateTime('now', new DateTimeZone("America/New_York")));
$startDate->modify("january")
->modify("first day of this month")
->modify("midnight");
$endDate->modify("next year")
->modify("january")
->modify("first day of this month")
->modify("midnight")->modify("-1 second");
var_dump([$startDate, $endDate]);
Try out here: https://www.tehplayground.com/Qk3SkcrCDkNJoLK2
Another way to do this is to separate the relative strings with a comma like so:
$startDate = (new DateTime('first day of january', new DateTimeZone("America/New_York")));
$endDate = (new DateTime('next year, first day of january, -1 second', new DateTimeZone("America/New_York")));
var_dump([$startDate, $endDate]);
Try out here: https://www.tehplayground.com/hyCqXLRBlhJbCyks
Basically date('Y') returns the value of current year. and the first day of each year starts like 2000-01-01.
So this will help you to get exact output.
$firstdate = date( 'Y' ) . '-01-01';
Take a look at this link -- http://davidhancock.co/2013/11/get-the-firstlast-day-of-a-week-month-quarter-or-year-in-php/
function firstDayOf($period, DateTime $date = null)
{
$period = strtolower($period);
$validPeriods = array('year', 'quarter', 'month', 'week');
if ( ! in_array($period, $validPeriods))
throw new InvalidArgumentException('Period must be one of: ' . implode(', ', $validPeriods));
$newDate = ($date === null) ? new DateTime() : clone $date;
switch ($period) {
case 'year':
$newDate->modify('first day of january ' . $newDate->format('Y'));
break;
case 'quarter':
$month = $newDate->format('n') ;
if ($month < 4) {
$newDate->modify('first day of january ' . $newDate->format('Y'));
} elseif ($month > 3 && $month < 7) {
$newDate->modify('first day of april ' . $newDate->format('Y'));
} elseif ($month > 6 && $month < 10) {
$newDate->modify('first day of july ' . $newDate->format('Y'));
} elseif ($month > 9) {
$newDate->modify('first day of october ' . $newDate->format('Y'));
}
break;
case 'month':
$newDate->modify('first day of this month');
break;
case 'week':
$newDate->modify(($newDate->format('w') === '0') ? 'monday last week' : 'monday this week');
break;
}
return $newDate;
}
in PHP 5.3.10 this works
$myDate = new \DateTime(date("Y")."-01-01");
echo $myDate->format("Y-m-d");
In PHP 5.4 and upper you can put all together
echo (new \DateTime(date("Y")."-01-01"))->format("Y-m-d")
As a commenter #Glavić said already
$year = new DateTime('first day of January');
is the solution.
To me it did make sense semantically that "this year" should return midnight of the first day of the year, but indeed it does not!
Following is the code snippet for getting first and last day of the year.
$firstDayOfYear = date('Y-01-01');
$lastDayOfYear = date('Y-12-t');
Try this:
$dt = date('m/d/Y',time());
echo 'First day : '. date("01/01/Y", strtotime($dt)).' - Last day : '. date("m/t/Y", strtotime($dt));
Getting first and last day of the current year using DateTime object.
$currentDate = new \DateTime("NOW");
$yearStartString = $currentDate->format("Y")."-01-01 00:00:00";
$yearEndString = $currentDate->format("Y")."-12-31 23:59:59";
$yearStartDate = \DateTime::createFromFormat("Y-m-d H:i:s", $yearStartString);
$yearEndDate = \DateTime::createFromFormat("Y-m-d H:i:s", $yearEndString);
I have a PHP DateTime object that looks like this...
$startdate = '01/05/2019';
$mydate = DateTime::createFromFormat("d/m/Y", $startdate);
Is there a way to advance this date to the nearest 17th of the month? The start date will be dynamic so I cant hardcode it.
Does anybody have an example?
Add one day to your date until you find the next 17th.
<?php
$startdate = '2019-01-05';
$interval = new DateInterval('P1D'); // define interval as 1 day
$date = new DateTime($startdate);
while($date->format('j') != 17){
$date->add($interval);
}
echo $date->format('Y-m-d') . "\n";
Output: 2019-01-17
The trick here is to find the first date of the appropriate month, then add sixteen days.
These modify() expressions are helpful.
$mydate->modify ("first day of this month")->modify("+ 16 days");
$mydate->modify ("first day of next month")->modify("+ 16 days");
Next, you can figure out which one you want:
if ($mydate->format("d") > 17) ...
Put it all together like this:
$mydate = DateTime::createFromFormat("d/m/Y", $startdate);
if ($mydate->format("d") > 17) {
$mydate->modify ("first day of this month")->modify("+ 16 days");
}
else {
$mydate->modify ("first day of next month")->modify("+ 16 days");
echo $mydate->format('Y-m-d') . "<br/>\r\n";
And, when you test this sort of thing, be sure to test it with days in December and February to ensure the year-rollover and month-rollover logic works correctly.
So, in PHP i'm trying to return a date value for last year based on the same day of week.
EX: (Monday) 2011-12-19 inputted should return (Monday) 2010-12-20.
I was just doing it simply by -364 but then that was failing on leap years. I came across another function :
$newDate = $_POST['date'];
$newDate = strtotime($newDate);
$oldDate = strtotime('-1 year',$newDate);
$newDayOfWeek = date('w',$oldDate);
$oldDayOfWeek = date('w',$newDate);
$dayDiff = $oldDayOfWeek-$newDayOfWeek;
$oldDate = strtotime("$dayDiff days",$oldDate);
echo 'LAST YEAR DAY OF WEEK DATE = ' . date('Ymd', $oldDate);
however, that is failing when you try to input a Sunday date, as it does a 0 (sunday) minus 6 (saturday of last year date), and returns with a value T-6. IE inputting 2011-12-25 gets you 2010-12-19 instead of 2011-12-26.
I'm kind of stumped to find a good solution in php that will work for leap years and obviously all days of the week.
Any suggestions?
Thanks!
How about this, using PHP's DateTime functionality:
$date = new DateTime('2011-12-25'); // make a new DateTime instance with the starting date
$day = $date->format('l'); // get the name of the day we want
$date->sub(new DateInterval('P1Y')); // go back a year
$date->modify('next ' . $day); // from this point, go to the next $day
echo $date->format('Ymd'), "\n"; // ouput the date
$newDate = '2011-12-19';
date_default_timezone_set('UTC');
$newDate = strtotime($newDate);
$oldDate = strtotime('last year', $newDate);
$oldDate = strtotime(date('l', $newDate), $oldDate);
$dateFormat = 'Y-m-d l w W';
echo "This date: ", date($dateFormat, $newDate), "\n";
echo "Old date : ", date($dateFormat, $oldDate);
That gives:
This date: 2011-12-19 Monday 1 51
Old date : 2010-12-20 Monday 1 51
Use strtotime() to get a date, for the same week last year.
Use the format {$year}-W{$week}-{$weekday}, like this:
echo date("Y-m-d", strtotime("2010-W12-1"));
And you can do that for as long back you wan't:
<?php
for($i = 2011; $i > 2000; $i--)
echo date("Y-m-d", strtotime($i."-W12-1"));
?>
Make it easier :)
echo date('Y-m-d (l, W)').<br/>;
echo date('Y-m-d (l, W)', strtotime("-52 week"));
Edit: I forgot to write output: :)
2015-05-06 (Wednesday, 19)
2014-05-07 (Wednesday, 19)
<?php
$date = "2020-01-11";
$newdate = date("Y-m-d",strtotime ( '-1 year' , strtotime ( $date ) )) ;
echo $newdate;
?>
ref https://www.nicesnippets.com/blog/how-to-get-previous-year-from-date-in-php