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

PhpDatetimeTimezone

Php Problem Overview


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.

Php Solutions


Solution 1 - 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

Solution 2 - Php

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

Solution 3 - Php

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

Solution 4 - Php

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.

Solution 5 - Php

Another quick way:

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

Solution 6 - Php

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);

Solution 7 - Php

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

Solution 8 - Php

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

Solution 9 - Php

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);
}

Solution 10 - Php

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);
}

Solution 11 - Php

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.

Solution 12 - Php

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionvarun View Question on Stackoverflow
Solution 1 - PhpBotond BéresView Answer on Stackoverflow
Solution 2 - PhptranteView Answer on Stackoverflow
Solution 3 - PhpcjohanssonView Answer on Stackoverflow
Solution 4 - Phpvarun View Answer on Stackoverflow
Solution 5 - PhpAndreView Answer on Stackoverflow
Solution 6 - PhpnickfView Answer on Stackoverflow
Solution 7 - PhpKaliumView Answer on Stackoverflow
Solution 8 - PhpHerdplattenToniView Answer on Stackoverflow
Solution 9 - Phpuser2214236View Answer on Stackoverflow
Solution 10 - PhpDrinkynetView Answer on Stackoverflow
Solution 11 - PhpVadim SamokhinView Answer on Stackoverflow
Solution 12 - Phpraafet dhaouadiView Answer on Stackoverflow