How to Convert a Date into User's Timezone Using PHP & JavaScript

I needed to convert a date that is in PST (GMT-8) to date based on user's timezone.
I had to find a way to get user's timezone and pass it to php so it can do the conversion.

Here's the approach: Guess the timezone using momentjs and pass it to php and let it do the conversion.

Steps
1. Download the minified versions of momentjs & momentjs-timezone
http://momentjs.com/timezone/

2. Include the files in your page

[code]
<script src="share/momentjs/moment.min.js"></script>
<script src="share/momentjs/moment-timezone-with-data-2010-2020.min.js"></script>
[/code]

3. Guess the timezone with JavaScript

[code]
var tz = '';

try {
// moment js + moment timezone
tz = moment.tz.guess();
} catch (e) {}

// use tz and pass it to php via ajax or in a hidden field
// index.php?tz=America/Toronto
[/code]

4. Use it in php

[code]
<?php $tz = empty( $_REQUEST['tz'] ) ? '' : $_REQUEST['tz'];
$date = date( 'Y-m-d H:i:s' );
echo "The date is: " . orbisius_date_util::correct_date( $date, $tz );

class orbisius_date_util {
    /**
     * Recalculates the dates from one (base) timezone to another.
     * We're using momentjs to detect user's timezone which is passed with the search filters.
     * orbisius_date_util::correct_date();
     *
     * @param str $starting_date - July 6, 2016 14:00:00, 2016-11-26 6pm, 2016-11-26 22:00:00
     * @param str $user_tz
     * @return str
     */
    public static function correct_date( $starting_date, $user_tz = 'America/Toronto', $fmt = 'Y-m-d H:i:s' ) {
        try {
            // if the user timezone is invalid we won't modify the date.
            $date = $starting_date;
            
            // http://php.net/manual/en/datetime.settimezone.php
            $base_tz = new DateTimeZone( 'America/Vancouver' );
            $date_obj = new DateTime( $starting_date, $base_tz );
            $date_obj->setTimezone( new DateTimeZone( $user_tz ) );

            $date = $date_obj->format( $fmt );
        } catch ( Exception $e ) {
            // Probably wrong date timezone.
        }

        return $date;
    }
}

[/code]

Related
http://momentjs.com/timezone/
http://stackoverflow.com/questions/11883757/convert-utc-datetime-to-another-timezone-php
http://stackoverflow.com/questions/2505681/timezone-conversion-in-php

Referral Note: When you purchase through a referral link (if any) on this page, we may earn a commission.
If you're feeling thankful, you can buy me a coffee or a beer