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
Related
I'm working on a PHP function which calculates holidays:
function holidays($country = 1, $timespan_start = 0, $timespan_end = 0)
The holidays are returned as timestamps in an array.
Since I have to calculate dates like the first Monday of February, I tried strtotime("first monday february $year") and I've discovered that this does not work for 2010, since 02/01/2010 is a Monday - I get February 8th instead.
This bug is actually mentioned in the change log:
In PHP 5 prior to 5.2.7, requesting a given occurrence of a given weekday in a month where that weekday was the first day of the month would incorrectly add one week to the returned timestamp. This has been corrected in 5.2.7 and later versions.
But I'm using PHP 5.3.8.
Why am I experiencing this error?
Looks like you are just missing an "of":
echo date('Y-m-d', strtotime('first monday of february 2010'));
will give the expected result. See the PHP Manual on Relative dates for the various input formats.
Depending on your version of PHP the 'of' statement may or may not work. As another solution try:
echo date('Y-m-d',strtotime('monday February 2010'));
will return the first monday of February 2010. Works for all days as well.
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
I am using a date() format to return the starting weekday of a month. The code I have below is how I am attempting to achieve this. For the current year (2018) this works as normal. For example This month is august and the starting weekday is a Wednesday so it will return a 3 for Wednesday. (It works so far)
As we advance the year to 2019 it starts to get the starting weekday wrong.
For example January 2019 starts on a Tuesday so it should return 2 but returns 1. (one day out)
This error seems to be cumulative so if we go to 2020 then it is 2 days out etc.
I have tried so hard to format this Date() correctly but to no avail. Is this even the correct way to do this?
Code:
$future_month = 5 /*for January 2019*/
$starting_weekday = date('N',mktime(0, 0, 0, date('m', strtotime('+'.$future_month.' months', strtotime(date('Y-m-01')))), 1));
Many Thanks
Cameron
Your code makes this much more complicated than it needs to be.
$dt = new DateTime('first day of +5 months')
$dt->format('N'); // "2"
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).
function DateFormat($dt)
{
return $newDate = date("d/m/Y", strtotime($dt));
}
$cr='2014-02-31';
echo DateFormat($cr);
Input: $cr='2014-02-31';
Output: 03/03/2014
I am passing 2014-02-31 and getting output 03/03/2014.
Please help me out.
PHP's date functions work with dates not strings. And that's an important distinction. Strings are just a bunch of characters in a specified order. Dates have months, days, years, hours, minutes, seconds, timezones, etc. When PHP works with dates it takes all of them into consideration.
So when you pass Feb 31 to a PHP date function it is going to try to make sense of it as a date and not a string. This means it isn't just going to take that date cut it up into bits and then rearrange them as you are expecting. It is going to turn that date into a date representation it can work with and then manipulate it.
As we all know, February does not have 31 days. As a result of the invalid date, PHP is trying to be helpful and taking three days after last day in February of that year (since Feb only has 28 days this year) and giving you that date.
The issue is February most years only has 28 days. 2/31 would be logically translated to 3/3. On a leap year you'd get 3/4...
The strtotime() method as it needs to be very flexible to be able to handle stuff without borking like:
strtotime('2014 February + 31 day - 1 year');
And no I don't think it should error out. When you have a well formed date string, PHP has a deceptively named method called checkdate() you could use:
$crappy_date='2014-02-31';
$date_parts = explode('-', $crappy_date);
$valid = checkdate($date_parts[1], $date_parts[2], $date_parts[0]);