1

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

1
  • DateTime::createFromFormat(); perhaps? Commented Oct 7, 2013 at 19:46

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes DateTime and DateInterval classes are must learn when it comes to manipulating dates in PHP>
This works well, thanks. However it replaces the fraction with timezone information (+02:00) to comply with the ISO8601 format. Should I change the string output with substr_replace() or try to modify the date format?
0
$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");

1 Comment

John types faster than me and probably has the more efficient answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.