php time converter

  • panzhuli
  • Graduate
  • Graduate
  • panzhuli
  • Posts: 135
  • Loc: Cleveland

Post 3+ Months Ago

Hi there -

I have to convert a date from an xml feed. The feed comes in like this:

08/23/2010, or DD/MM/YYYY

and they want me to turn it around to MM/DD/YYYY. why they don't just spit it out that way is beyond me... anyways...

Is there a php widget to do that? I'd hate to sniff for the "/" characters and do it that way... I couldn't find anything on php[dot]net that sounded right to me...

thanks!
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

There's strptime, but there's a bunch of nasty notes on the manual page. If you're on Windows the function isn't even an option.

strtotime seems to be out of the question, I believe it interprets dates in the format you're aiming for, rather than the one you're converting from. I'm not sure whether this is affected by locale settings or not.

You could preg_replace it.
PHP Code: [ Select ]
$date = preg_replace('#(\d{2})/(\d{2})/(\d{2}|\d{4})#', '$2/$1/$3', $str);
  • panzhuli
  • Graduate
  • Graduate
  • panzhuli
  • Posts: 135
  • Loc: Cleveland

Post 3+ Months Ago

this works well! Now they want me to trim the YYYY to just YY. Is there a way to do that in that pattern?
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

PHP Code: [ Select ]
$date = preg_replace('#(\d{2})/(\d{2})/(?:\d{2})?(\d{2})#', '$2/$1/$3', $str);
  • panzhuli
  • Graduate
  • Graduate
  • panzhuli
  • Posts: 135
  • Loc: Cleveland

Post 3+ Months Ago

impressive. thanks! someday i'll understand what that pattern says lol
  • joebert
  • Fart Bubbles
  • Genius
  • User avatar
  • Posts: 13502
  • Loc: Florida

Post 3+ Months Ago

It says "find two digits and save them as $1, then find a forward slash, then find two digits and save them as $2, then find a forward slash, look for two digits but don't fail if you don't find them and don't remember them if they're there, then find two digits and remember them as $3".

In the second argument of preg_replace it says "replace the entire string that was matched by the pattern with the value of $2, followed by a forward slash, followed by the value of $1, followed by a forward slash, and finally the value of $3".

Post Information

  • Total Posts in this topic: 6 posts
  • Users browsing this forum: No registered users and 75 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
cron
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.