Adding 1 day to day of week (Monday, Tuesday..) [duplicate] - php

This question already has answers here:
Adding days to $Date in PHP
(12 answers)
Closed 3 years ago.
Without knowing or using any kind of date, what's the best way to just add 1 day to the day of the week?
For example, I have Monday and I want to add +1 Days. Something like this
echo ('Monday + 1 days');
I tried with date(); but couldn't find a solution. Any ideas?

You can simply do:
<?php
echo date('l', strtotime('Monday + 1 day'));
We just use the strtotime logic of adding a time period and wrap it in a date format of l - which is full text representation of the day.
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
refs:
https://secure.php.net/manual/en/function.strtotime.php
https://secure.php.net/manual/en/function.date.php

There is no built-in function in PHP that says "the day after Monday is Tuesday" without referring to a particular Monday (which is what strtotime would do). Of course, you may choose to not care that they refer to a particular Monday and Tuesday, since the pattern hasn't changed recently and will not change in the foreseeable future.
You can use an if statement or a switch-case statement. You can even make it work in a different language.
if ($date === "lundi") return "mardi";
if ($date === "mardi") return "mercredi";
// etc

Related

How to get full date from string without having the actual month in the string in PHP?

Is there any way to get the full date from a string that does not actually contain the month?
i am given the date in a format of Wednesday 16th and need to add this to my database with a month,
The application i am making is for lifestyle couriers and they get their manifests in that format and have the last 2 months available, so i need to find out the month?
Assuming that you want to regard the current and the last two months, I can imagine, that there will be no two day numbers of the same week day in that timespan (that should be proven first).
I would iterate back over the last n days using PHP's date function and try to detect your "Wednesday 16th" where n is the aggregate of month days that date with param "t" returns for the current and the last two months.
If you have your match then, you know the month and the year (the year could be the previous year as well if you start in January or February).
You can do it like this:
<?php
$date = 16;
$day = "Wednesday";
$oneMonthAgo = explode(" ",date("m Y F",strtotime("-1 month")));
$twoMonthsAgo = explode(" ",date("m Y F",strtotime("-2 months")));
if (date("l",strtotime($date."-".$oneMonthAgo[0]."-".$oneMonthAgo[1]))==$day) {
echo "Last month: ".$oneMonthAgo[2];
}
else if (date("l",strtotime($date."-".$twoMonthsAgo[0]."-".$twoMonthsAgo[1]))==$day) {
echo "Month before last: ".$twoMonthsAgo[2];
}
else {
echo "Not valid";
}
?>
Explanation
Because you are using PHP, there is an easy way to do this. In other languages, you would have to use a weekday algorithm.
In PHP, we can convert a properly formatted string into a time, from which we can then derive date information. Examples of a properly formatted string is -1 month or -2 months, which return time objects for the previous month or the month before that, respectively.
Using the date() function, we can get the month, year and textual month values for those months. We delimiter these by a space, so that we can explode these values into an array after they are found. Thus, we now have two arrays, $oneMonthAgo and $twoMonthsAgo, which both contain their month's respective number, year and textual month at the 0, 1 and 2 indexes respectively.
Now, we can create another time, by appending the date that we are looking for ($date) onto these values, with the proper delimiters in-between (when using - as the delimiters, PHP assumes a d-m-Y format, when using / PHP assumes a m-d-Y format). Then, by passing that through another date() function, we can find the data that we are looking for: the textual day that took place at that date. Now we can simply compare that to the day that we are looking for, $day. If the textual day is the same, then this is the month which we are looking for, so we can print out the full textual month.
We do this in an if / else statement for both months, and if we still haven't found it, assume that the date is invalid.
Notes
References to the PHP functions used can be found on the PHP Manual: date() function, strtotime() function, Valid dates for strtotime()
Yes and no. Since full date requires month to be known you need to know what to do with lack of that information. If you "guess" the month (be it current one or random, does not matter), then "yes" is close. If you cannot tell what the month we talk about then answer is no (or random).
PS: you may need a year too...
I use a while loop to loop backwards however many months needed to find what is searched for.
$date = 16;
$day = "Wednesday";
$x=0;
$start = date("Y-m-") . $date;
While(date("l", strtotime($start ."-" .$x . "months")) != $day){
$x++;
}
Echo $x . " months ago.";
// Or to output the date:
//Echo date("Y-m-d", strtotime($start ."-" .$x . "months"));
https://3v4l.org/vUYeX
This will output 0 months ago.
But if input $date= 15; it will output 5 months ago (March 2017).

PHP date function is returning wrong month and date [duplicate]

This question already has answers here:
strtotime on incorrect dates
(2 answers)
Closed 5 years ago.
I have been working in PHP Development for 5 years but never seen this type of error before.
I have a date which is the last day of the month and I am going to change its format with using below code :
$data['toDate'] = "2017-04-31";
echo $data['toDate']." : ".date('d-m-Y',strtotime($data['toDate']))." ### ";
die;
It outputs :
2017-04-31 00:00:00 : 01-05-2017 ###
I am working on PHP version 5.6.25.
Is there anyone can help me in this??
The 31th April don't exist. Because of that PHP going to the day after the 30th April
April only has 30 days, so it's actually correcting the date your using. The 31st would really be the 1st of May.
Its wrong with input, not with date().
$data['toDate'] = "2017-04-31";// no 31st in 4th(April) month
echo $data['toDate'] ." : ". date('d-m-Y',strtotime($data['toDate']))." ### ";
die;
Its just showing up next date which is 01-05-2017
tl;dr
04-31 is valid but not technically a date in April, since April only has 30 days and thus strtotime() yields 05-01.
Documentation
If you look at the documentation for strtotime() you will see the first parameter is:
time
A date/time string. Valid formats are explained in Date and Time Formats.
If you follow the link for the date and time formats and go to Date Formats you will see:
Thus for the date format (I.e. DD), 01-31 is valid (since a 3 can only be followed by a 0 or 1) despite the month. Depending on the supplied month and date value the date will be adjusted.
Also found in the notes on that same page:
Note:
It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes "2008-08-00" equivalent to "2008-07-31" and "2008-06-31" equivalent to "2008-07-01" (June only has 30 days).1
Hence 04-31 is valid but overflows.
Additionally, in the User Contributed Notes section, the note by Mirek at 2015-04-01 01:14 might be useful/interesting:
Note: the day (dd or DD) is first checked for range 0..31 and only if it fits, the overflow and underflow mechanism may apply. If not, strtotime() simply returns false.
If you need unlimited over/underflow for date calculations (for example 2015-01-40 to 2015-02-09), use mktime() instead.2
1http://php.net/manual/en/datetime.formats.date.php
2http://php.net/manual/en/datetime.formats.date.php#Hcom117014

How to get last "particular (Ex. March)" month in PHP?

I want to display the last March month. I am using the following code,
date("Y-m-d",strtotime("last March"));
Any suggestions or references would be very helpful.
$year = date('Y');
if (date('n') < 3) {
$year--;
}
$beginningOfLastMarch = mktime(0, 0, 0, 3, 1, $year);
See http://php.net/date
date('M')
or
date('n')
or
date('m')
or, if you have a date
$mydate = "2010-05-12 13:57:01";
you can get like this
$month = date("m",strtotime($mydate));
m Numeric representation of a month, with leading zeros 01 through 12
n Numeric representation of a month, without leading zeros 1 through 12
I found a better way to do this but left my old solution at the bottom, as it may still be relevant for some people in certain use cases.
I found a better solution to my problem which involves prepending a date to strtotime, and then using the relative selectors. Say I wanted to select the 4th of March last year. I just do:
strtotime('{THIS_YEAR}-03-04 last year');
Obviously, before processing this string, I would replace {THIS_YEAR} with date('Y'). This works, simply because I hard code the values I want. 03-04 as 4th of March. I can replace these numbers with any date I like.
Old Solution
I figured out a solution that worked for me and it doesn't really involve writing any complex algorithms or anything. It does involve slightly extending the syntax of strtotime though.
Even though PHP's strtotime isn't perfect (for all use cases), I found that if you join strtotime's together, then you can make it extremely powerful.
Say if I wanted to select the 4th of last month, I can't really do that... strtotime doesn't really accept ordinals. I.E 4th.
However, I can do first day of last month, which is pretty close. All I need is to change the day.
strtotime allows a time() to be passed as a second argument. This means you can chain strtotime's like so:
$time = time();
$time = strtotime('first day of last month', $time);
$time = strtotime('+3 days', $time);
echo date('Y-m-d H:i', $time);
// I know we don't really need the initial `$time = time()`. It is there for clarity
which will give us the right time: 4th of last month.
This is where a little syntactic sugar comes in...
We can write a function that accepts partial strtotime strings separated by a delimeter:
function my_strtotime($str, $time = null, $delim = '|'){
$time = ($time==null ? time() : $time);
foreach(explode($delim, $str) as $cmd){
$time = strtotime($cmd, $time);
}
return $time;
}
Which can be used like so:
$str = 'first day of last month | +3 days';
echo date('Y-m-d H:i', my_strtotime($str));
And there we have it. 4th of last month.
There is no need to strip whitespace from the explode call, because strtotime already handles extra whitespace.
This can handle complex intervals like last year | first day of March | +9 days | 14:00 which will always return 10th of March at 2pm last year.
The best thing about this is that strings like last year | first day of March | +9 days | 14:00 can be generated with the required values, E.G.
last year | first day of {MONTH} | +{DAYS-1} days | {TIME}
This might need extra work to improve it, but I just wanted to quickly get this out here, so it may help others reaching this question

get the last thursday before a date in PHP

I know there is similar post about how to get the last Thursday in PHP but I don't want to have the last Thursday compare to the current date but the last Thursday compare to a given date.
For example I have a date dd/mm/yyyy and I want the Thursday before this date.
The input is a String ( the format of the string yymmdd) that I want to parse to get the Thursday before this date.
Thanks for your help
//Assumes it's strtotime parsable, you may need to insert
// slashes with your given format eg (and use 4 digit years)
$given=strtotime($dtstring);
//It's just that easy ;)
$thuBefore=strtotime("last thursday",$given);
Note that this will always get last thursday, meaning if the given date is a Thursday, it'll report 7 days earlier (but if the date's a Friday it'll only report one day earlier).
$day = date('w', $yourTime);
$time = $yourTime - ($day > 4 ? ($day - 4) : ($day + 7 - 4)) * 3600 * 24;
Where both $yourTime and $time are Unix-timestamps.
Edit: #Rudu's solution is way more simple, you should stick with that one :)!

Month by week of the year?

I'm trying to get the number of the month of the year by the number of a week of the year and the year.
So for example week 1 is in january and returns 1, week 6 is in february so I want 2.
I tried to go with date_parse_from_format('W/Y') but had no success (it's giving me errors).
Is there any way to go with date_parse_from_format() or is there another way?
print date("m",strtotime("2011-W6-1"));
(noting that in 2011, January has six weeks so week 6 (by some definitions) is in month 1).
Just wanted to add a note for the first answer, the week number should be 01-09 for Weeks 1 through 9 (it will always give month 1 if you don't add the leading zero)
date("m",strtotime("2011-W06-1"));
Using PHP DateTime objects (which is the preferred way of dealing with dates see links below for more info) you can accomplish it this way:
$dateTime = new \DateTime();
$dateTime->setISODate($year,$week);
$month = $dateTime->format('n');
Note that the following will not work as week "W" is not a supported format:
$month = \DateTime::createFromFormat("W/Y ", "1/2015")->format('n');
The format used by this method is the same supported by the function you where trying to use date_parse_from_format, hence the errors.
Why PHP DateTime Rocks
DateTime class vs. native PHP date-functions
strtotime notes
PHP/Architect's Guide to Date and Time Programming (Chapter 2)
Something like this will do, this is also tested and works:
function getMonthByNumber($number,$year)
{
return date("F",strtotime('+ '.$number.' weeks', mktime(0,0,0,1,1,$year,-1)));
}
echo getMonthByNumber(27,2011);
Hope this helps

Categories