Date to milliseconds / milliseconds to date

ぃ、小莉子 提交于 2019-12-02 15:43:09

问题


I have a date in milliseconds. obtained with something like:

SELECT EXTRACT(MILLISECONDS FROM NOW())

How do I revert to a date again?

I've tried with:

SELECT TO_TIMESTAMP(EXTRACT(MILLISECONDS FROM NOW()))

The above returns a date in 1970 ...


回答1:


EXTRACT(MILLISECONDS ...) gets you (per documentation) ...

The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.

Just test with:

SELECT now(), EXTRACT(MILLISECONDS FROM NOW()) AS millisec;

The rest is in the manual as well:

epoch

For timestamp with time zone values, the number of seconds since 1970-01-01 00:00:00 UTC (can be negative); for date and timestamp values, the number of seconds since 1970-01-01 00:00:00 local time; for interval values, the total number of seconds in the interval

SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2001-02-16 20:38:40.12-08');
*Result: 982384720.12*

SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
*Result: 442800*

Here is how you can convert an epoch value back to a time stamp:

SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 982384720.12 * INTERVAL '1 second';

(The to_timestamp function encapsulates the above conversion.)




回答2:


EXTRACT doesn't get you date in milliseconds. I think that should work:

SELECT EXTRACT(EPOCH FROM NOW()) * 1000;
SELECT TO_TIMESTAMP(EXTRACT(EPOCH FROM NOW()))

Found here



来源:https://stackoverflow.com/questions/25384348/date-to-milliseconds-milliseconds-to-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!