Anthony
Anthony

Reputation: 481

Date with the correct time

I used date to get the date but...

It's 3 hours off from my computer time.

This date('g:i A')

Is giving a time EST I believe because I'm PST and it's 3 hours off.

Is there a way to get it to put the correct time zone automatically?

Upvotes: 0

Views: 64

Answers (3)

Peter
Peter

Reputation: 31701

The robust solution is to use DateTime with DateTimeZone instead of date:

<?php

$date = new \DateTime(null, new \DateTimezone('PST'));
// or even better: 
$date = new \DateTime(null, new \DateTimezone('America/Los_Angeles'));

$formatted = $date->format('g:i A');

Note that just using a generic timezone such as 'PST' may still be ambiguous. Some locations in that timezone may be observing DST, some may not. Thus, the only reliable thing to do is to specify the location as concrete as possible.

Upvotes: 1

Mark King
Mark King

Reputation: 36

To simply get the time 3 hours from the server you can say:

date ('g:i A', time () + 60*60*3);

or

date ('g:i A', time () - 60*60*3);

To my knowledge there is not a "perfect" way to get the timezone a user is in, but in the past I have used javascript to find out the user's current computer time and compare that to the server's time. Javascript is the only method I know of for getting any information related to someone's current time or timezone.

Upvotes: 1

Kermit
Kermit

Reputation: 34055

You can configure the timezone in your configuration file (php.ini) or at run time. PHP is a server side application, so it can't "automatically" get the time zone from the client.

Documentation

If you're working with data, you should use UTC date/time and offset the time appropriately.

Upvotes: 1

Related Questions