Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get week number (in the year) from a date PHP

Tags:

date

php

mktime

I want to take a date and work out its week number.

So far, I have the following. It is returning 24 when it should be 42.

<?php $ddate = "2012-10-18"; $duedt = explode("-",$ddate); $date = mktime(0, 0, 0, $duedt[2], $duedt[1],$duedt[0]); $week = (int)date('W', $date); echo "Weeknummer: ".$week; ?> 

Is it wrong and a coincidence that the digits are reversed? Or am I nearly there?

like image 815
AJFMEDIA Avatar asked Mar 05 '12 13:03

AJFMEDIA


People also ask

How to get week of year from date in php?

php $ddate = "2012-10-18"; $duedt = explode("-",$ddate); $date = mktime(0, 0, 0, $duedt[2], $duedt[1],$duedt[0]); $week = (int)date('W', $date); echo "Weeknummer: ".

How to get week number from date php?

How to get the week number from a date. To get the ISO week number (1-53) of a date represented by a Unix timestamp, use idate('W', $timestamp ) or strftime('%-V', $timestamp ) .

How to use the date function in php?

It is possible to use date() and mktime() together to find dates in the future or the past. $tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y")); $lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y")); $nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.


1 Answers

Today, using PHP's DateTime objects is better:

<?php $ddate = "2012-10-18"; $date = new DateTime($ddate); $week = $date->format("W"); echo "Weeknummer: $week"; 

It's because in mktime(), it goes like this:

mktime(hour, minute, second, month, day, year); 

Hence, your order is wrong.

<?php $ddate = "2012-10-18"; $duedt = explode("-", $ddate); $date  = mktime(0, 0, 0, $duedt[1], $duedt[2], $duedt[0]); $week  = (int)date('W', $date); echo "Weeknummer: " . $week; ?> 
like image 195
Madara's Ghost Avatar answered Oct 13 '22 04:10

Madara's Ghost