4

I display the date or the time on my website a lot and I'm thinking about writing a function to parse a PostgreSQL timestamp.

The timestamp is in the format: Y-m-d H:i:s.u. E.g. 2011-04-08 23:00:56.544.

I'm thinking about something like this:

function parse_timestamp($timestamp, $format = 'd-m-Y')
{
    // parse the timestamp

    return $formatted_timestamp;
}

However I am wondering whether this can also be achieved without writing a parser for it myself (with the use of some PHP function).

PeeHaa
  • 71,436
  • 58
  • 190
  • 262

5 Answers5

5
function parse_timestamp($timestamp, $format = 'd-m-Y')
{
    return date($format, strtotime($timestamp));
}

Don't forget to set timezone before, e.g.

date_default_timezone_set('UTC');

Or in your case, I guess 'Europe/Amsterdam'.

You can always get PHP timestamp of this format Y-m-d H:i:s.u using strtotime(). Then, using date() you can export time in your own format. Both functions depend of time zone set.

Wh1T3h4Ck5
  • 8,399
  • 9
  • 59
  • 79
4

strtotime is perfectly capable of parsing that time string, then just reformat it with date:

echo date('d-m-Y', strtotime('2011-04-08 23:00:56.544')); // 08-04-2011
netcoder
  • 66,435
  • 19
  • 125
  • 142
3

For those using DateTime class:

DateTime::createFromFormat('Y-m-d H:i:s.u', $yourTime);
Savas Vedova
  • 5,622
  • 2
  • 28
  • 44
2

If the database isn't giving you what you want, change it. PostgreSQL can also format dates and times.

select to_char(timestamp '2011-03-04 07:04:00', 'DD-MM-YYYY');
04-03-2011

But that's risky in international contexts, like the web. Different locales expect different ordering of elements. (Does "04-03" mean 03-April or 04-March?) This expression is easier to understand, and it uses locale-specific abbreviations for the months.

select to_char(timestamp '2011-03-04 07:04:00', 'DD-Mon-YYYY');
04-Mar-2011
Mike Sherrill 'Cat Recall'
  • 91,602
  • 17
  • 122
  • 185
0

Take a look at the strptime function - it can parse many time formats.

dog
  • 390
  • 2
  • 8