Question

This is my first post. I have a problem that i can't seem to resolve. Here it goes:

I have a PHP script that prints the date of an event to the page:

$event_datetime = date("g:i A (m/d/y)", strtotime($row['event_time']));
echo $event_datetime

I want to use Javascript to convert that $event_datetime into client local timezone preferably or local client computer time.

Any ideas ?

Thanks in advance !

Was it helpful?

Solution 2

You can use php to convert all dates into a timezone with:

date_default_timezone_set('America/Los_Angeles');

For example:

$time = time();
$date = date(DATE_RFC822, $time);
echo $date . PHP_EOL;

date_default_timezone_set("Australia/Perth");
$date = date(DATE_RFC822, $time);
echo $date. PHP_EOL;

Output:

Mon, 19 Aug 13 18:49:40 +0000
Tue, 20 Aug 13 02:49:40 +0800

You would just need to get the clients timezone from somewhere (a preference saved in the database or getting it via javascript for example).

See Getting the client's timezone in JavaScript for using javascript

OTHER TIPS

Instead of echoing a date to javascript, just echo the timestamp and use javascripts date object.

var date = new Date(<?php echo strtotime($row['event_time']) * 1000); ?>);

You can now use javascripts date object to print out the time however you want. Like this:

date.toLocaleDateString();
//The default output will be the users' timezone (the client where the javascript is being executed), but can be configured with the options argument

See:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

For more on the javascript date object

I got the answer to what i was looking for, but i thank you guys for taking the time to help. Your solution was great but not what i needed. Ok, here is how i got it:

Keeping in mind that $row['event_time'] is a datetime value saved on the database on UTC timezone.

while($row = $result->fetch_assoc())
{
    $s_date = new DateTime($row['event_time'],new DateTimeZone('UTC'));
    $s_date->setTimezone(new DateTimeZone('America/New_York'));
    $start_event_time = $s_date->format('g:i:s A (m/d/y)');
    echo $start_event_time;
}

You can create an additional script that gets the current user timezone and change America/New_York to make it more dynamic.

Hope it helps someone with my same issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top