postgresql 解析psql时间戳的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5601505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-20 22:57:12  来源:igfitidea点击:

Function to parse psql timestamp

phppostgresqltimestamp

提问by PeeHaa

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.

我经常在我的网站上显示日期或时间,我正在考虑编写一个函数来解析 PostgreSQL 时间戳。

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

时间戳的格式为:Y-m-d H:i:s.u. 例如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).

但是我想知道这是否也可以在不为它自己编写解析器的情况下实现(使用一些 PHP 函数)。

回答by Wh1T3h4Ck5

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'.

或者在你的情况下,我猜'Europe/Amsterdam'

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

您始终可以Y-m-d H:i:s.u使用strtotime(). 然后,使用date()您可以以您自己的格式导出时间。这两个功能都取决于时区设置。

回答by netcoder

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

strtotime完全有能力解析那个时间字符串,然后用date重新格式化它:

echo date('d-m-Y', strtotime('2011-04-08 23:00:56.544')); // 08-04-2011

回答by Mike Sherrill 'Cat Recall'

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

如果数据库没有给你你想要的,改变它。PostgreSQL 还可以格式化日期和时间

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.

但这在国际环境中是有风险的,比如网络。不同的语言环境期望元素的不同顺序。(“04-03”是指 03-April 还是 04-March?)这个表达更容易理解,它使用特定于语言环境的月份缩写。

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

回答by Savas Vedova

For those using DateTime class:

对于那些使用 DateTime 类的人:

DateTime::createFromFormat('Y-m-d H:i:s.u', $yourTime);

回答by dog

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

看看这个strptime函数——它可以解析多种时间格式。