PHP week date conversion - php

My date formatted like this "2000-5-1". First digit represents 4 digit year. The second is number of week in year, and the last one represents number of day in week.
No matter what I do, function always returns false, my code is following:
date_create_from_format("Y-W-N", "2000-5-1")
(docs)
Please avoid solutions that are using magic words like "+1 day" etc.

Creating a DateTime object from a compound format with year/week/day is described in the compound formats section of the supported date and time formats section of the PHP Docs:
$x = new DateTime("2000-W05-1");
var_dump($x);
Note that the week number requires a leading zero
Result is a DateTime object for 2000-01-31

If you look at the documantation of DateTime::createFromFormat (which is what you are using with an alias) and date(), there is not a 100% overlap of the formats, so you have a problem.
This is what I found that you could use as an alternative: DateTime::setISODate
$date = explode('-','2000-5-1');
$newDate = new DateTime();
$newDate->setISODate($date[0], $date[1], $date[2]);
setISODate will take the year, week and day as explained in the documentation to create a DateTime object.

Related

Check day and difference time of a date

I have this date / time value (with timezone):
2019-10-22T17:00:00+02:00
Now I would like to check, which weekday this date is (for example: Monday)
and if this date has a difference of 1h between 16:00 o'clock and the date time.
How can I check the two factors as best practice ?
You may use DateTimeImmutable's constructor to parse the date string, DateTime#format to format it / retrieve the week day, and DateTime#diff to fetch the difference:
$date_string = '2019-10-22T17:00:00+02:00';
$date = new \DateTimeImmutable($date_string);
$date_at_16 = $date->setTime(16, 0);
echo $date->format('l'), PHP_EOL;
echo $date->diff($date_at_16)->h;
Demo: https://3v4l.org/R7e9n
Note that:
I've used DateTimeImmutable which is just like DateTime except it cannot be modified, so setTime doesn't also modify the initial date,
you should catch its constructor's potential thrown exception (if the format is invalid),
it should be better to use 'N' to retrieve the day of the week, as it's numerical and therefore more appropriate to store/compare (I've used 'l' for the purpose of this little demo, to get the full name),
if you need to know if it's 1 hour prior to or following 16 o'clock, you may check the DateInterval#invert flag (the date interval is what DateTime#diff returns).

PHP convert week number and year back to Carbon?

I'm using format W-Y for weeknumber & year.
e.g. the final week of 2018 would be represented as '52-2018'.
But I can't get Carbon or DateTime to convert it back.
>>> Carbon::createFromFormat('W-Y', '01-2018')
InvalidArgumentException with message 'The format separator does not match
The separation symbol could not be found
Trailing data'
DateTime::createFromFormat (which is what Carbon extends) doesn't support the W formatting character, unfortunately.
The easiest way to work around this is to create a new DateTime (or Carbon) instance, and use the native setISODate method to set the year and week number:
$str = '01-2018';
list ($week, $year) = explode('-', $str);
$d = new DateTime;
$d->setISODate($year, $week);
See https://3v4l.org/g33QV
A string of the form '01-2018' can also be converted to '2018W01' with preg_replace, which can then be processed directly by DateTime and Carbon.
$str = '01-2018';
$dateTime = new DateTime(preg_replace('~^(\d\d)-(\d\d\d\d)$~','$2W$1',$str));
While with the accepted solution we always get the current time for the date, here it is always 00:00:00.
Demo: https://3v4l.org/mo6dQ

Convert and insert two date formats MYSQL

I'm facing an issue with managinging dates, some dates pass others dont. I want to produce an insertable date for mysql. there are two possible types of post dates
yyyy-mm-dd //should go without conversion
m/d/yyyy // should be converted
I'm using this
$date = $_REQUEST['date'];
$date_regex = '/(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/';
if(preg_match($date_regex, $date)){
$date = DateTime::createFromFormat('m/d/Y',$date)->format('Y-m-d');}
problems
I realised this regex is failing for dates like
2/5/2013
but has been working for
12/12/2013
so I removed it BUT still
DateTime::createFromFormat('m/d/Y',$date)->format('Y-m-d');
is also failing for m/d/yyyy
This date thing has got my head spinning for the last 6 hours.
In this case, there is no need to use DateTime::createFromFormat because m/d/yyyy is one of the recognized date formats (see "American month, day and year"). Just convert it to a DateTime object and let the constructor handle the format and forget the regex:
$date = $_REQUEST['date'];
$datetime = new DateTime($date);
$datex = $datetime->format('Y-m-d');
The reason DateTime::createFromFormat('m/d/Y',$date) fails for dates like 2/5/2013 is because you are forcing it to be specifically 'm/d/Y' and that date does not fit that pattern. You can see a list of all date formats here. Specifically, m expects there to be a leading zero (like 02), so when you give it one without that, it won't recognize it. Same goes for d. In this case you would have to use n and j respectively. But, like I said, let the constructor do the hard work for you.

Date('now') in PHP

After a long time I needed to use date function of PHP. I wrote something like:
echo date('now');
and I got the output below:
1220123
What does that mean ?
From the PHP manual :
n Numeric representation of a month, without leading zeros
o ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that
year is used instead. (added in PHP 5.1.0)
w Numeric representation of the day of the week
So, date("now") displays 12 (n), 2012 (o) and 3 (w).
You're probably looking for :
date("Y-m-d") for a date
date("Y-m-d H:i:s") for a datetime
"now" is not a valid parameter for for this expectation, infact it should be strtotime function here, not date.
Date considers your now as
n
Numeric representation of a month, without leading zeros
o
ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)
w
Numeric representation of the day of the week
you need to give a valid format to date function (not recognize the 'now' string as meaning of now )
$date = date("Y-m-d H:i:s");
or you can use the DateTime class
$date = new DateTime();
Seems you consider "now" as a word to get the current date and time, however it would compile on each character. Here is the explanation how it'll compile.
n = Month in number
o = It considers as a year in ISO-8601.
w = Week in number
So that's why it's returning you the date, year and number of week in a month.
Hope I can explain you bit easily.
"now" is not a valid parameter for date()
Correct syntax to print current date in
yyyy-mm-dd hours minutes seconds
format is as given below
echo date('Y-m-d h:i:s');
also see PHP manual for details of date() function
http://php.net/manual/en/function.date.php

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