php date day of week

PHP get start and end date of a week by weeknumber

I’ve seen some variants on this question but I believe this one hasn’t been answered yet.

I need to get the starting date and ending date of a week, chosen by year and week number (not a date)

The return value will be something like an array in which the first entry is the week starting date and the second being the ending date.

OPTIONAL: while we are at it, the date format needs to be Y-n-j (normal date format, no leading zeros.

I’ve tried editing existing functions that almost did what I wanted but I had no luck so far.

Please help me out, thanks in advance.

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

15 Answers 15

A shorter version (works in >= php5.3):

Many years ago, I found this function:

We can achieve this easily without the need for extra computations apart from those inherent to the DateTime class.

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

Slightly neater solution, using the «[year]W[week][day]» strtotime format:

shortest way to do it:

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

You can get the specific day of week from date as bellow that I get the first and last day

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

The calculation of Roham Rafii is wrong. Here is a short solution:

if you want the last day of the week number, you can add up 6 * 24 * 3600

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

This is an old question, but many of the answers posted above appear to be incorrect. I came up with my own solution:

First we need a day from that week so by knowing the week number and knowing that a week has seven days we are going to do so the

this way pickAday will be a day in our desired week.

Now because we know the year we can check which day is that. things are simple if we only need dates newer than unix timestamp We will get the unix timestamp for the first day of the year and add to that 24*3600*$pickADay and all is simple from here because we have it’s timestamp we can know what day of the week it is and calculate the head and tail of that week accordingly.

Источник

How to find day of week in php in a specific timezone

I am confused while using php to handle date/time.

What I am trying to do is this: When a user visits my page I am asking his timezone and then displaying the ‘day of week’ in his timezone.

I don’t want to use the browser’s day. I want to do this calculation in php.

This is how I am trying to achieve it:

But I dont know how to proceed. How would i get the ‘day of week’ in this timezone.

12 Answers 12

My solution is this:

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

I think this is the correct answer, just change Europe/Stockholm to the users time-zone.

ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday)

Thanks a lot guys for your quick comments.

This is what i will be using now. Posting the function here so that somebody may use it.

Report if you find any corrections.

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

If you can get their timezone offset, you can just add it to the current timestamp and then use the gmdate function to get their local time.

This should work (didn’t test it, so YMMV). It works by storing the script’s current timezone, changing it to the one specified by the user, getting the day of the week from the date() function at the specified timestamp, and then setting the script’s timezone back to what it was to begin with.

You might have some adventures with timezone identifiers, though.

«Day of Week» is actually something you can get directly from the php date() function with the format «l» or «N» respectively. Have a look at the manual

edit: Sorry I didn’t read the posts of Kalium properly, he already explained that. My bad.

Check date is monday or sunday before get last monday or last sunday

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

Based on one of the other solutions with a flag to switch between weeks starting on Sunday or Monday

Standard letter-based representations of date parts are great, except the fact they’re not so intuitive. The much more convenient way is to identify basic abstractions and a number of specific implementations. Besides, with this approach, you can benefir from autocompletion.

For more about this approach, take a look here.

Источник

Php date day of week

(PHP 4, PHP 5, PHP 7, PHP 8)

date — Форматирует вывод системной даты/времени

Описание

Список параметров

Возвращаемые значения

Ошибки

Список изменений

ВерсияОписание
8.0.0timestamp теперь допускает значение null.

Примеры

Пример #1 Примеры использования функции date()

// установка часового пояса по умолчанию.
date_default_timezone_set ( ‘UTC’ );

// выведет примерно следующее: Monday
echo date ( «l» );

// выведет примерно следующее: Monday 8th of August 2005 03:12:46 PM
echo date ( ‘l jS \of F Y h:i:s A’ );

/* пример использования константы в качестве форматирующего параметра */
// выведет примерно следующее: Mon, 15 Aug 2005 15:12:46 UTC
echo date ( DATE_RFC822 );

Чтобы запретить распознавание символа как форматирующего, следует экранировать его с помощью обратного слеша. Если экранированный символ также является форматирующей последовательностью, то следует экранировать его повторно.

Пример #2 Экранирование символов в функции date()

Пример #3 Пример совместного использования функций date() и mktime()

Данный способ более надёжен, чем простое вычитание и прибавление секунд к метке времени, поскольку позволяет при необходимости гибко осуществить переход на летнее/зимнее время.

Пример #4 Форматирование с использованием date()

// Предположим, что текущей датой является 10 марта 2001, 5:16:18 вечера,
// и мы находимся в часовом поясе Mountain Standard Time (MST)

$today = date ( «F j, Y, g:i a» ); // March 10, 2001, 5:16 pm
$today = date ( «m.d.y» ); // 03.10.01
$today = date ( «j, n, Y» ); // 10, 3, 2001
$today = date ( «Ymd» ); // 20010310
$today = date ( ‘h-i-s, j-m-y, it is w Day’ ); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date ( ‘\i\t \i\s \t\h\e jS \d\a\y.’ ); // it is the 10th day.
$today = date ( «D M j G:i:s T Y» ); // Sat Mar 10 17:16:18 MST 2001
$today = date ( ‘H:m:s \m \i\s\ \m\o\n\t\h’ ); // 17:03:18 m is month
$today = date ( «H:i:s» ); // 17:16:18
$today = date ( «Y-m-d H:i:s» ); // 2001-03-10 17:16:18 (формат MySQL DATETIME)
?>

Примечания

Смотрите также

User Contributed Notes 20 notes

Things to be aware of when using week numbers with years.

Conclusion:
if using ‘W’ for the week number use ‘o’ for the year.

In order to define leap year you must considre not only that year can be divide by 4!

The correct alghoritm is:

if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)

So the code should look like this:

For Microseconds, we can get by following:

echo date(‘Ymd His’.substr((string)microtime(), 1, 8).’ e’);

FYI: there’s a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:

echo date ( ‘Y-m-d\TH:i:sO’ );
?>

You can use

echo date ( DateTime :: ISO8601 );
?>

instead, which is much easier to read.

this how you make an HTML5 tag correctly

It’s common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP’s built-in functions. Consider http://php.net/manual/en/function.date.php#108613

date() will format a time-zone agnostic timestamp according to the default timezone set with date_default_timezone_set(. ). Local time. If you want to output as UTC time use:

$tz = date_default_timezone_get ();
date_default_timezone_set ( ‘UTC’ );

For HTML5 datetime-local HTML input controls (http://www.w3.org/TR/html-markup/input.datetime-local.html) use format example: 1996-12-19T16:39:57

To generate this, escape the ‘T’, as shown below:

If timestamp is a string, date converts it to an integer in a possibly unexpected way:

The example below formats today’s date in three different ways:

The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)

This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.

At least in PHP 5.5.38 date(‘j.n.Y’, 2222222222) gives a result of 2.6.2040.

So date is not longer limited to the minimum and maximum values for a 32-bit signed integer as timestamp.

Prior to PHP 5.6.23, Relative Formats for the start of the week aligned with PHP’s (0=Sunday,6=Saturday). Since 5.6.23, Relative Formats for the start of the week align with ISO-8601 (1=Monday,7=Sunday). (http://php.net/manual/en/datetime.formats.relative.php)

This can produce different, and seemingly incorrect, results depending on your PHP version and your choice of ‘w’ or ‘N’ for the Numeric representation of the day of the week:

Prior to PHP 5.6.23, this results in:

Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 10 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 10 Oct 2016

Since PHP 5.6.23, this results in:

Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 03 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 03 Oct 2016

I’ve tested it pretty strenuously but date arithmetic is complicated and there’s always the possibility I missed something, so please feel free to check my math.

The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. «skip all Fridays and Saturdays but include Sundays») or to set up dates that should always be skipped (e.g. «skip July 4th in any year, skip the first Monday in September in any year»). But that’s a project for another time.

$start = strtotime ( «1 January 2010» );
$end = strtotime ( «13 December 2010» );

// Add as many holidays as desired.
$holidays = array();
$holidays [] = «4 July 2010» ; // Falls on a Sunday; doesn’t affect count
$holidays [] = «6 September 2010» ; // Falls on a Monday; reduces count by one

?>

Or, if you just want to know how many work days there are in any given year, here’s a quick function for that one:

Источник

Get Start and End Days for a Given Week in PHP

I realized all it did was add 7 days to the current date. How would you do this?

16 Answers 16

I would take advantange of PHP’s strtotime awesomeness:

Tested on the data you provided and it works. I don’t particularly like the whole reference thing you have going on, though. If this was my function, I’d have it be like this:

And call it like this:

I’m not a big fan of doing math for things like this. Dates are tricky and I prefer to have PHP figure it out.

To everyone still using mktime(), strtotime() and other PHP functions. give the PHP5 DateTime Class a try. I was hesitant at first, but it’s really easy to use. Don’t forget about using clone() to copy your objects.

Edit: This code was recently edited to handle the case where the current day is Sunday. In that case, we have to get the past Saturday and then add one day to get Sunday.

Then format as you need it.

Make sure to set your timezone early in your code.

Apparently ‘w’ formatting value of date() or the format method of a DateTime object will return the day of the week as a number (by default, 0=Sunday, 1=Monday, etc)

You could take this and subtract it’s value as days from the current day to find the beginning of the week.

$start_date will now be equal to the Sunday of that week, from there you can add 7 days to get the end of the week or what-have-you.

Base on @jjwdesign’s answer, I developed a function that can calculate the beginning and ending of a week for a specific date using the DateTime class. WILL WORK ON PHP 5.3.0++

The difference is you can set the day you want as the «beginning» between 0 (monday) and 6 (sunday).

Here’s the function :

Here’s my version, which uses a similar notion to Clay’s:

Lightly tested. Code may not be bulletproof, or handle dates in the far past or future. Use at your own risk. Do not immerse the code in water. Do not show the code to those of a nervous disposition, or with a hatred of the dollar sign. Not tested on animals. Safe for use by vegetarians. Author warrants that the code will never, ever speak to you. In the unlikely event that the code does try to engage you in conversation, the author advises you to disregard any and all advice it gives.

Use this to get the «week» number from any given date.

Now pass the parameters for getWeekDates function as «year (2009)» and «$week».

php date day of week. Смотреть фото php date day of week. Смотреть картинку php date day of week. Картинка про php date day of week. Фото php date day of week

In trying to find a more streamlined version of the accepted answer by Paolo Bergantino, I discovered a really nice way to get this done:

The ‘sunday this week’ string always means «The Sunday at the end of this week.» If used on a timestamp that falls on a Sunday, it will be the following Sunday. This lets you avoid the need for the ternary operator in Paola’s solution.

You can now use DateTime to get start/end dates of week(s)

Usage

To be honest, I have trouble understanding the code you posted 😉

I guess something like this should do the trick:

Without doing so much string manipulation, you can do some simple math on the timestamps.

Based on David Bélanger’s version (unfortunatelly, my rep. won’t allow me to post comment as reaction to his post..).

When input date is monday and first day of week is set as monday, original version returns previous week, not current. Here’s the little fix (with the rest of orig. function):

A simple code to return the days from start DateTime and end DateTime. Using gmdate() method you can format date/time.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *