Question

PHP question related to manipulating a time variable.

Situation: Reading from mysql and converting to UTC datetime:

myelement_info["ItemDate"]=$dbrecord->created_at

This sets ItemDate to full UTC time: 2014-05-09T13:54:22Z

Good, but I need the seconds to always be ignored/truncated in ItemDate. E.g. if the db says: 2014-05-09T13:54:22Z

I need ItemDate to be: 2014-05-09T13:54:00Z // note the 00Z

And if the db says: 2014-05-09T13:54:59Z

I need ItemDate to be the same: 2014-05-09T13:54:00Z // again, 00Z

Basically, I need a UTC date, but always need to ignore the seconds in the db (because they move when they should not). This is not "rounding" to nearest minute (rounding does not meet my needs). This is "ignoring seconds."

I do not want to do this by string manipulation, because I am worried I can't test all permutations and will mangle the data in some situations. For example, there could be region specific settings on a mysql or php environment that would give a different format to the UTC rendering of the datetime.

I want code that reads from the db field into a proper datetime variable, and to chop the seconds properly, on the datetime variable, and then cast the variable to string.

Was it helpful?

Solution

Just change the format of the date and hard code 00 seconds:

$date = new DateTime('2014-05-09T13:54:00Z');
echo $date->format('Y-m-d\TH:i:00\Z');

Demo

As a one-liner:

echo (new DateTime('2014-05-09T13:54:00Z'))->format('Y-m-d\TH:i:00\Z');

OTHER TIPS

You could try the strtotime function and pass that result to the date function:

date($format, strtotime($dbrecord->created_at))

where $format is the format string you want as described at the php.net manual.

Note: You may need to set the timezone with, e.g., date_default_timezone_set('UTC');

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