[php] 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:

  1. The timezone entered by user
  2. Unix time stamp calculated by php time() function.

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

This question is related to php datetime timezone

The answer is


"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.


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.

// let's say they're in the timezone GMT+10
$theirOffset = 10;  // $_GET['offset'] perhaps?
$offsetSeconds = $theirOffset * 3600;
echo gmdate("l", time() + $offsetSeconds);

$myTimezone = date_default_timezone_get();
date_default_timezone_set($userTimezone);
$userDay = date('l', $userTimestamp);
date_default_timezone_set($myTimezone);

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.


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

function getWeekForDate($date, $weekStartSunday = false){

    $timestamp = strtotime($date);

    // Week starts on Sunday
    if($weekStartSunday){
        $start = (date("D", $timestamp) == 'Sun') ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('Last Sunday', $timestamp));
        $end = (date("D", $timestamp) == 'Sat') ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('Next Saturday', $timestamp));
    } else { // Week starts on Monday
        $start = (date("D", $timestamp) == 'Mon') ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('Last Monday', $timestamp));
        $end = (date("D", $timestamp) == 'Sun') ? date('Y-m-d', $timestamp) : date('Y-m-d', strtotime('Next Sunday', $timestamp));
    }

    return array('start' => $start, 'end' => $end);
}

echo date('l', strtotime('today'));

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

 public function getWeek($date){
    $date_stamp = strtotime(date('Y-m-d', strtotime($date)));

     //check date is sunday or monday
    $stamp = date('l', $date_stamp);      
    $timestamp = strtotime($date);
    //start week
    if(date('D', $timestamp) == 'Mon'){            
        $week_start = $date;
    }else{
        $week_start = date('Y-m-d', strtotime('Last Monday', $date_stamp));
    }
    //end week
    if($stamp == 'Sunday'){
        $week_end = $date;
    }else{
        $week_end = date('Y-m-d', strtotime('Next Sunday', $date_stamp));
    }        
    return array($week_start, $week_end);
}

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.

public function getDayOfWeek($pTimezone)
{

    $userDateTimeZone = new DateTimeZone($pTimezone);
    $UserDateTime = new DateTime("now", $userDateTimeZone);

    $offsetSeconds = $UserDateTime->getOffset(); 
    //echo $offsetSeconds;

    return gmdate("l", time() + $offsetSeconds);

}

Report if you find any corrections.


Another quick way:

date_default_timezone_set($userTimezone);
echo date("l");

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.

Since we're talking about datetimes here, it seems plausible that the basic abstraction is ISO8601DateTime. One of the specific implementations is current datetime, the one you need when a makes a request to your backend, hence Now() class. Second one which is of some use for you is a datetime adjusted to some timezone. Not surprisingly, it's called AdjustedAccordingToTimeZone. And finally, you need a day of the week in a passed datetime's timezone: there is a LocalDayOfWeek class for that. So the code looks like the following:

(new LocalDayOfWeek(
    new AdjustedAccordingToTimeZone(
        new Now(),
        new TimeZoneFromString($_POST['timezone'])
    )
))
    ->value();

For more about this approach, take a look here.


My solution is this:

$tempDate = '2012-07-10';
echo date('l', strtotime( $tempDate));

Output is: Tuesday

$tempDate = '2012-07-10';
echo date('D', strtotime( $tempDate));

Output is: Tue


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

$dateTime = new \DateTime(
    'now',
    new \DateTimeZone('Europe/Stockholm')
);
$day = $dateTime->format('N');

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

http://php.net/manual/en/function.date.php

For a list of supported time-zones, see http://php.net/manual/en/timezones.php


$dw = date( "w", $timestamp);

Where $dw will be 0 (for Sunday) through 6 (for Saturday) as you can see here: http://www.php.net/manual/en/function.date.php


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to datetime

Comparing two joda DateTime instances How to format DateTime in Flutter , How to get current time in flutter? How do I convert 2018-04-10T04:00:00.000Z string to DateTime? How to get current local date and time in Kotlin Converting unix time into date-time via excel Convert python datetime to timestamp in milliseconds SQL Server date format yyyymmdd Laravel Carbon subtract days from current date Check if date is a valid one Why is ZoneOffset.UTC != ZoneId.of("UTC")?

Examples related to timezone

How to set the timezone in Django? How to convert Moment.js date to users local timezone? What does this format means T00:00:00.000Z? How do I get the current timezone name in Postgres 9.3? MySQL JDBC Driver 5.1.33 - Time Zone Issue Python get current time in right timezone Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings PHP date() with timezone? How to store a datetime in MySQL with timezone info Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST