views:

97

answers:

3
function convertDT($TS) {
    $TS = strtotime($TS);
    $TS -= date("Z");
    $newTS = date("Y-m-d\TH:i:s\Z", $TS);
    return $newTS;
}

echo "Good: ".convertDT('2010-04-20 01:23:45')."\n";
echo "Bad: ".convertDT('2010-31-20 01:23:45')."\n";

The second date returns: 1969-12-31T23:00:00Z

Why? Should this error?

A: 

On your second date, you are trying to create a date of month 31 and of day 20. Even if you reversed these, it wouldn't make sense. Probably a typo.

ryeguy
yes, I want to validate and throw an error instead of returning the 1969 date
Phill Pafford
@Phill: `strtotime` is erroring out because you're giving it a bogus date. You can check to see if it returns FALSE on error. In the second line of your example, you're basically doing `0 - date('Z')` everytime, because FALSE is getting casted to 0.
ryeguy
A: 

read this http://php.net/manual/en/function.strtotime.php

Errors/Exceptions

Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()

This function will not generate any error even if input string is not valid.

vooD
+3  A: 

strtotime() returns false when you give it an invalid timestamp. false is equivalent to 0 if you use it in an integer context, so when you pass it to this line:

$newTS = date("Y-m-d\TH:i:s\Z", $TS);

You are effectively creating a date from a timestamp of 0. In terms of the UNIX epoch, 0 is January 1st, 1970, which is where you're getting your end result from.

Your best bet would be soemthing like this:

$TS = strtotime($TS);
if($TS === false) {
    throw new Exception("Invalid timestamp.");
}
//etc.
zombat
Thanks, this is what I was looking for
Phill Pafford