Get Week Number From Date off one week - php

Trying to get the week number from a given date within PHP. For some reason various things I try seem to be a week off.
Looking at the following link we should be on week 3
http://www.epochconverter.com/date-and-time/weeknumbers-by-year.php
Yet when I do the following I get week 2
echo "Weeknummer: " . date("W", strtotime("2016-01-17"));
I've also tried this code getting the same result, week 2
$date = new DateTime("2016-01-17");
$week = $date->format("W");
echo "Weeknummer: $week";
Any ideas why its seems to be a week behind and how I can fix that?
Thanks

We are, but today is the 19th (at least in my time-zone...).
You have hard-coded the 17th in your script and as you can see in the site that you mentioned, that is the last day of week 2.

The link you sent shows that 2016-01-17 is on week 2. See screenshot. In PHP the weeks start on Monday (you can read more in the docs)

It's because in mktime(), it goes like this:
mktime(hour, minute, second, month, day, year);
so try with the below code hope it's what you want
<?php
$ddate = "2016-01-17";
$duedt = explode("-", $ddate);
$date = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]);
$week = (int)date('W', $date);
echo "Weeknummer: " . $week;
?>
also you can try github.com/briannesbitt/Carbon to maximize your skills in Date manipulation. For carbon you can do that by:
Carbon::createFromFormat('Y-m-d H', '2012-10-18')->format('W');

Related

PHP: Previous Month from current month formula is not working

It might be Duplicate Question, but I tried but it doesn't work.
Something confusion is there, which I am not getting it.I tried for all months its working but its not working for "March" Month.I know it sound weird, but I tried everything.
Aim: Show Previous Month from Given Month.
PHP:
$month='March';
$pre_mth =Date("F", strtotime($month . " last month"));
echo $pre_mth;
Actual Output: March Expected Output:February
Please let me know.Thanks in advance.
Try this:
$pre_mth = date('F',strtotime('first day of last month', strtotime($month)));
echo $pre_mth;
Extra space existed before "last month". Also, specify a day to avoid conflicts.
Try this:
$month = 'March 1';
$pre_mth = Date("F", strtotime($month . "last month"));
echo $pre_mth; // February

$date format("M y") always showing the wrong month (the one before)

I got this code:
list($year, $month, $day) = explode("-", $row['game_release']);
if (checkdate($month, $day, $year)) {
$date = (new DateTime($row['game_release']))->format("j M 'y");
} else {
$date = (new DateTime($row['game_release']))->format("M 'y");
}
echo"
<tr>
<td> ".$date." </td>
The reason why I need it, is because some dates are invalid 00-05-2015 for example. I use this to list games as announced, but without a confirmed release date. I realize they are invalid, but if I query for dates BETWEEN 2015-04-00 AND 2015-04-30 they show up under April like they should.
However, in the code above, which I'm using in my search engine, a game listed as 2015-04-00 would appear as 'March '15'. Why is this happening and how can I solve it?
Why is this happening
Because months usually start on day 1, thus day 0 is the previous month.
and how can I solve it?
else {
$date = (new DateTime(($day+1) . "$month-$year"))->format("M 'y");
}
As Marco Bernardini suggested add one day to the not released date and show the correct month.
If it were me. I would not rely on empty date alone. I would add a flag_release to the database table which I would verify as 0 everytime I show the upcoming releases.
$date = (new DateTime($row['game_release']));
$date->modify("+1 day");
echo $date->format("M 'y");

Get day most closely following today from list of days in PHP string

I need to look at the contents of a string and determine what the day most closely following today would be.
For example. lets say I have a string called $available_day_list with the value "monday, thursday, friday, saturday,."
According to the list above, If today was tuesday, I would like to display "thursday."
If today was saturday, I would like to display "tuesday."
I am getting the value of today with:
$current_day = date("l");
$current_day = strtolower($current_day);
Anyone know how I might be able to do this without an array? Thanks all!!
Try this:
$days = explode(',',$available_day_list);
$closestDay = '';
$minTime = 620000;// more than a week
foreach($days as $day){
$diff = strtotime('next '.$day) - time();
if($diff < $minTime){
$closestDay = $day;
$minTime = $diff;
}
}
echo $closestDay;
(i know, should've been written as a comment, but can't yet) Yotam's code turns the string into an array. And it works great, I'm not sure why you don't want to use arrays.
If you really don't though, you'll basically have to determine the current day, and then search through the string for the next day, and if not the next, and so on, until you find one.

Calculate date php issue with strtotime

Still trying to figure out date with PHP. I have this:
$fri_end_date = date('Y-m-d',strtotime('Friday'));
$fri_start_date = date('Y-m-d ',strtotime('Friday'));
$put = $fri_start_date.$fri_end_date;
echo "$put";
I want to calculate the date for each Friday but display that Friday date through till Sunday. Then on Monday it would show the next coming Friday. Basically want to show the same Friday date throughout the weekend. How would I do this?
I did understand your question now and I think this will solve your issue:
if( date('w') >= 6 )
$fri_end_date = date('Y-m-d',strtotime('last Friday'));
else
$fri_start_date = date('Y-m-d ',strtotime('Friday'));
$put = $fri_start_date.$fri_end_date;
echo "$put";
Using date('w') will return you the day of the week, that way you can test if it is saturday or sunday and use the 'last Friday' or else use the "current" Friday.
Cheers,
Denis
Try this and let me know if it is what you want:
$fri_end_date = date('Y-m-d',strtotime('last Friday'));
$fri_start_date = date('Y-m-d ',strtotime('next Friday'));
$put = $fri_start_date.$fri_end_date;
echo "$put";
This will display the date of the last Friday before the day you run the code and the next Friday.
Cheers,
Denis
The problem is that you are not really clear about your problem. That sayd, if I understand correctly you need to display 2 days before and after the current Friday. If that is the case try the code below.
$fri_end_date = date('Y-m-d',strtotime('Friday -2 days'));
$fri_start_date = date('Y-m-d ',strtotime('Friday +2days'));
$put = $fri_start_date.$fri_end_date;
echo "$put";
If it is not, try to be more concise and maybe throw in an example or two ;)
Cheers,
Denis

Can't get previous month from DateTime in PHP- Is this a (pretty big) bug?

I need to create functions in PHP that let me step up/down given datetime units. Specifically, I need to be able to move to the next/previous month from the current one.
I thought I could do this using DateTime::add/sub(P1M). However, when trying to get the previous month, it messes up if the date value = 31- looks like it's actually trying to count back 30 days instead of decrementing the month value!:
$prevMonth = new DateTime('2010-12-31');
Try to decrement the month:
$prevMonth->sub(new DateInterval('P1M')); // = '2010-12-01'
$prevMonth->add(DateInterval::createFromDateString('-1 month')); // = '2010-12-01'
$prevMonth->sub(DateInterval::createFromDateString('+1 month')); // = '2010-12-01'
$prevMonth->add(DateInterval::createFromDateString('previous month')); // = '2010-12-01'
This certainly seems like the wrong behavior. Anyone have any insight?
Thanks-
NOTE: PHP version 5.3.3
(Credit actually belongs to Alex for pointing this out in the comments)
The problem is not a PHP one but a GNU one, as outlined here:
Relative items in date strings
The key here is differentiating between the concept of 'this date last month', which, because months are 'fuzzy units' with different numbers of dates, is impossible to define for a date like Dec 31 (because Nov 31 doesn't exist), and the concept of 'last month, irrespective of date'.
If all we're interested in is the previous month, the only way to gaurantee a proper DateInterval calculation is to reset the date value to the 1st, or some other number that every month will have.
What really strikes me is how undocumented this issue is, in PHP and elsewhere- considering how much date-dependent software it's probably affecting.
Here's a safe way to handle it:
/*
Handles month/year increment calculations in a safe way,
avoiding the pitfall of 'fuzzy' month units.
Returns a DateTime object with incremented month/year values, and a date value == 1.
*/
function incrementDate($startDate, $monthIncrement = 0, $yearIncrement = 0) {
$startingTimeStamp = $startDate->getTimestamp();
// Get the month value of the given date:
$monthString = date('Y-m', $startingTimeStamp);
// Create a date string corresponding to the 1st of the give month,
// making it safe for monthly/yearly calculations:
$safeDateString = "first day of $monthString";
// Increment date by given month/year increments:
$incrementedDateString = "$safeDateString $monthIncrement month $yearIncrement year";
$newTimeStamp = strtotime($incrementedDateString);
$newDate = DateTime::createFromFormat('U', $newTimeStamp);
return $newDate;
}
Easiest way to achieve this in my opinion is using mktime.
Like this:
$date = mktime(0,0,0,date('m')-1,date('d'),date('Y'));
echo date('d-m-Y', $date);
Greetz Michael
p.s mktime documentation can be found here: http://nl2.php.net/mktime
You could go old school on it and just use the date and strtotime functions.
$date = '2010-12-31';
$monthOnly = date('Y-m', strtotime($date));
$previousMonth = date('Y-m-d', strtotime($monthOnly . ' -1 month'));
(This maybe should be a comment but it's to long for one)
Here is how it works on windows 7 Apache 2.2.15 with PHP 5.3.3:
<?php $dt = new DateTime('2010-12-31');
$dt->sub(new DateInterval('P1M'));
print $dt->format('Y-m-d').'<br>';
$dt->add(DateInterval::createFromDateString('-1 month'));
print $dt->format('Y-m-d').'<br>';
$dt->sub(DateInterval::createFromDateString('+1 month'));
print $dt->format('Y-m-d').'<br>';
$dt->add(DateInterval::createFromDateString('previous month'));
print $dt->format('Y-m-d').'<br>'; ?>
2010-12-01
2010-11-01
2010-10-01
2010-09-01
So this does seem to confirm it's related to the GNU above.
Note: IMO the code below works as expected.
$dt->sub(new DateInterval('P1M'));
Current month: 12
Last month: 11
Number of Days in 12th month: 31
Number of Days in 11th month: 30
Dec 31st - 31 days = Nov 31st
Nov 31st = Nov 1 + 31 Days = 1st of Dec (30+1)

Categories