2

Here my function that i try to trasform dates into different formats.

/*  example:
*   dateString          =   '03/25/2010';
*   inputDateFormat     =   '%m/%d/%Y';
*   ouputDateFormat     =   'Y-m-d';
*   return              ->  '2010-03-25';
*/  
function formatDate($dateString,$inputFormat=NULL,$outputFormat=NULL){
    if($dateString==''||$dateString==NULL) return '';
    $t =  strptime($dateString,$inputFormat);
    return gmdate($outputFormat,mktime($t[tm_sec],$t[tm_min],$t[tm_hour],($t[tm_mon]+1),($t[tm_mday]+1),($t[tm_year]+1900)));
}

My problem is

when i try to convert this date Wed, 19 Jan 2011 21:16:37 +0000 into 2011-01-19 21:16:37 with the following line:

echo formatDate('Wed, 19 Jan 2011 21:16:37 +0000','%a, %d %b %Y %H:%M:%S','Y-m-d H:i:s');

the result is this:

2011-01-21 11:16:21

why i'm getting the date with 2 days extra. Do you have any idea?

2 Answers 2

5

use this instead:

  function formatDate($dateString, $outputFormat=NULL){
      return date($outputFormat, strtotime($dateString));
  }

  echo formatDate('Wed, 19 Jan 2011 21:16:37 +0000','Y-m-d H:i:s');
Sign up to request clarification or add additional context in comments.

4 Comments

it works thank you :) but i need to specify the input format, too what do you suggest for this?
no problem, as a reminder, you should add validation in case you have an invalid date. before php 5.1 strtotime return -1, after it return FALSE.
when i give such date 03/02/2011 it cannot understand which one is day and which one is month :)
you can even put these: 'now', 'tomorrow' or 'now + 2 days' when you call formatDate
4

This is a wild guess, but maybe you need to set yoru time zone?

date_default_timezone_set() (requires PHP 5)

Comments

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.