Kadinski
Kadinski

Reputation: 161

Parsing and Modifying dates in PHP

I'm trying to parse a date from an XML file and return a date in a string in the same format as the original date, except 8 hours earlier.

The original date is in the following format:
'yyyy-mm-ddThh:mm:ss.ffff'
so that dates are always a fixed length.
Example: '2013-10-06T14:00:40.1000'

What would be an appropriate way to use the date_parse() and date_modify() functions in this situation?

Current code:

public function setTimeSeriesStartDate(){
    //FIXME
    //replace T with space to make it parsable by date_parse()
    $tempDate = $this->date;
    $tempDate[10] = ' ';
    $parsedDate = new DateTime(date_parse($tempDate));

    $parsedDate->modify('-'.$this->daysBeforeEvent.' day');
    $farmattedDate=$parsedDate->format('Y-m-d H:i:s');
    if($formattedDate){
        $this->timeSeriesStartDate= $formattedDate;
        $this->timeSeriesStartDate[10]='T';
    }
    else {$this->timeSeriesStartDate = $this->date;}
}

XML file the date is from: http://service.iris.edu/fdsnws/event/1/query?starttime=2010-02-27T06:30:00&endtime=2013-10-07&minmag=2.0&maxmag=4.5&includeallorigins=true&orderby=time&format=xml&limit=8&nodata=404

Corresponding issue on Github: https://github.com/felakuti4life/Seismokraft/issues/1

Upvotes: 1

Views: 110

Answers (2)

Anonymous Man
Anonymous Man

Reputation: 3056

$tempDate = $this->date;
$tempDate = date_add($tempDate,date_interval_create_from_date_string("-8 hours"));
$tempDate = date_format($tempDate,"Y/m/d H:i:s");

Upvotes: 0

John Conde
John Conde

Reputation: 219804

I think it's actually simpler than you've made it out to be. The following should work:

//$tempDate = $this->date; <-- REMOVE
//$tempDate[10] = ' '; <-- REMOVE
$parsedDate = new DateTime($tempDate);
$parsedDate->modify('-8 hours');

or

//$tempDate = $this->date; <-- REMOVE
//$tempDate[10] = ' '; <-- REMOVE 
$parsedDate = new DateTime($tempDate);
$parsedDate->sub(new DateInterval('PT8H'));

See it in action

Upvotes: 3

Related Questions