Home > Database > Mysql Tutorial > body text

使用 PostgreSQL 数据库日期类型的 4 个提示

WBOY
Release: 2016-06-07 17:31:40
Original
892 people have browsed it

当我们这些使用Rails的人看到例如5.weeks.from_nowor3.days.ago + 2.hours时并不会感到惊讶。同样,PostgreSQL也可以做到,你可以

当我们这些使用Rails的人看到例如5.weeks.from_nowor3.days.ago + 2.hours时并不会感到惊讶。同样,PostgreSQL也可以做到,你可以通过简单调用PostgreSQL内置函数来实现相同的功能。

相关阅读:

PostgreSQL删除表中重复数据行

PostgreSQL数据库连接池PgBouncer的搭建

Windows平台编译 PostgreSQL 

PostgreSQL备份心得笔记

PostgreSQL 的详细介绍:请点这里
PostgreSQL 的下载地址:请点这里

当前时间/日期/时间戳

获取当前时间的方式有很多种,在这之前我们需要知道以下两种类型的区别:

  • 总是返回当前的值 (clock_timestamp())
  • 总是返回当前值,但在事务中它返回的是事务开始的时间(now())
  • 让我们看下面这个例子

    postgres=# BEGIN;
    postgres=# SELECT now();
                  now
    -------------------------------
     2013-08-26 12:17:43.182331+02

    postgres=# SELECT now();
                  now
    -------------------------------
     2013-08-26 12:17:43.182331+02

    postgres=# SELECT clock_timestamp();
            clock_timestamp
    -------------------------------
     2013-08-26 12:17:50.698413+02

    postgres=# SELECT clock_timestamp();
            clock_timestamp
    -------------------------------
     2013-08-26 12:17:51.123905+02

    你会发现,语句执行时候clock_timestamp()的返回值每次都发生了改变,但是now()总是返回相同的值。当你需要考虑时区时,你应该特别注意这两个函数差异。

    时间区间:比如3天前

    使用interval操作符你可以轻松的构建一个时间区间,例如

    你可以看到,我们可以用interval操作符来简单的进行数学运算,这特别适合于构建例如3天前这样的时间区间,比如:

    postgres=# SELECT now() - interval '3 days';
              ?column?
    -------------------------------
     2013-08-23 12:23:40.069717+02

    获取星期几

    有些时候对于一个给定的时间,你仅仅只想知道的是这天是星期几或者是它属于那个世纪的更或者你只想知道它是一年中的第几天。PostgreSQL中的extract()函数提供了这种功能。

    如下例子是在8月26日 星期一进行测试的。

    postgres=# SELECT extract(DAY FROM now());
     date_part
    -----------
            26

    postgres=# SELECT extract(DOW FROM now());
     date_part
    -----------
            1

    extract()还有其他更强大的功能,,详情请参阅官方文档,在这里只列举了一小部分:

    linux

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!