tags:

views:

29

answers:

2

Hi guys,

I have a date string, say '2008-09-11'. I want to get a timestamp out of this, but I need to specify a timezone dynamically (rather then PHP default).

So to recap, I have two strings:

$dateStr = '2008-09-11';
$timezone = 'Americas/New_York';

How do I get the timestamp for this?

EDIT: The time of day will be the midnight of that day.... $dateStr = '2008-09-11 00:00:00';

+3  A: 
$date = new DateTime($dateStr, new DateTimeZone($timezone));
salathe
Do I not need to specify what timezone I am converting from? Or does it just convert from PHP default?
whydna
hah just was typing, you beat me :D
Joe Hopfgartner
@whydna you're not *converting* anything (unless I'm misreading). The code creates a representation of that date in the specified timezone.
salathe
I think you are converting. Because, it DOES matter what the original timezone for $dateStr is. So you need to somehow specify what timezone you are converting TO and what timezone you are converting FROM. But your example will work because the timezone it is converting FROM is the default php timezone.
whydna
@whydna No, you're not converting. You're *interpreting* the date string as if referred to the specified timezone. To convert you new `$d = new DateTime($dateStr, $timezonefrom); $d->setTimezone($timezoneto);`.
Artefacto
@Artefacto - if my $dateStr = '2008-09-11 00:00:00' does it not matter whether this original representation is in EST or PST? The timestamp would be different depending on which one it is, no? Maybe I am just confused :S
whydna
@whydna Yes, it would be different of course. But a time doesn't exist in a vacuum. It has an associated timezone. If you're going to lie as to the actual timezone when you create the `DateTime` object, that's your problem. But it's not a proper timezone conversion. A conversion entails going from one timezone to another. From where would you be converting in that case?
Artefacto
Artefacto, you're right. Just took me a bit to wrap my head around it. Thanks!
whydna
A: 
$reset = date_default_timezone_get();
date_default_timezone_set('Americas/New_York');
$stamp = strtotime($dateStr);
date_default_timezone_set($reset);
Jonah Bron
works but dont forget to change it back! i think salathes solution is better
Joe Hopfgartner
What do you mean "change it back"? Yeah, 1 line vs. 4 lines. Hmmm. :D
Jonah Bron
This solution (which isn't quite what the OP wants, which is why i made it a comment) is great if the entire application needs to run on a particular timezone for that process - just not near as elegant for a one time need.
Dan Heberden