• 0

How to fomat the time from a string using PHP?


Question

Hello

I have a script that writes the time to a DB in this format: 20021231051742. This number is in ISO format I believe. I need to extract this number and format it in to something most people can read. The number above means "31st of December 2002. 05:17:42 AM".

However, the code that I am using, parses this data as "8/3/1909 5:36AM", yeah, very wrong! :x

Anyway, I was wondering if someone can help? I am *VERY* new at PHP.

Here is the code I am using:

date_format($post_data["datestamp"])

Thank you.

Ash

Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

I've found a solution. Just in case there are any new PHP developers out there, here is how I solved it:

$timedate = $post_data["datestamp"];
 ?$xyear=substr($timedate,0,4);
 ?$xmonth=substr($timedate,4,2);
 ?$xday=substr($timedate,6,2);
 ?$xhour=substr($timedate,8,2);
 ?$xmin=substr($timedate,10,2);
 ?$xsec=substr($timedate,12,2);
 ?$timedate=date('D jS F, Y. g:i:sA.', mktime($xhour,$xmin,$xsec,$xmonth,$xday,$xyear));
 echo $timedate;

Link to comment
Share on other sites

  • 0

Actually, a regular expression may be better for the purpose, as it won't barf all over you if there is malformed input. I think this code should work (although, it's untested :) ):

$time_data = array();
preg_match( '([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})', $post_data["datestamp"], $time_data );

$time_data should be an array of your matched data. Indices 1-6 should be year through secs (index 0 is the whole string). An empty array is returned if there was no match (aka malformed input).

Link to comment
Share on other sites

  • 0

Thank you Timdorr.

I am very new at this and am on a slight learning curb but most of the syntax of the language looks fairly similar to JS, C and Perl, which helps a lot.

I am wondering if you know of any sites with lots of example code that I can learn from?

Thanks

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.