代码之家  ›  专栏  ›  技术社区  ›  Deian

如何解析带日期的时区

  •  3
  • Deian  · 技术社区  · 7 年前

    如何让date实用程序解析时区字符串?

    $>date -d "2018-02-21T02:22:33.221" "+%Y-%m-%dT%H:%M:%S.%3N %Z"
    2018-02-20T14:22:33.221 EST
    

    但是

    $>date -d "2018-02-21T02:22:33.221 EST" "+%Y-%m-%dT%H:%M:%S.%3N %Z"
    date: invalid date `2018-02-21T02:22:33.221 EST'
    

    这是本地信息:

    $>uname -r
    2.6.32-696.13.2.el6.x86_64
    
    $>date
    Tue Jan 16 09:58:52 EST 2018
    
    $>date --version
    date (GNU coreutils) 8.4
    Copyright (C) 2010 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.
    
    Written by David MacKenzie.
    
    2 回复  |  直到 7 年前
        1
  •  3
  •   Viktor Khilin    7 年前

    ISO8601 允许您替换 T 有空间。只要这样做,您的命令就会正常工作:

    # date -d "2018-02-21T02:22:33.221 EST" "+%Y-%m-%dT%H:%M:%S.%3N %Z"
    date: invalid date `2018-02-21T02:22:33.221 EST'
    

    但是:

    # date -d "2018-02-21 02:22:33.221 EST" "+%Y-%m-%d %H:%M:%S.%3N %Z"
    2018-02-21 10:22:33.221 MSK
    
        2
  •  1
  •   Nahuel Fouilleul    7 年前

    date -d date +format ,它只能接受来自 man date

      -d, --date=STRING
              display time described by STRING, not `now'
    DATE STRING
       The  --date=STRING  is  a  mostly  free  format  human  readable  date string such as "Sun, 29 Feb 2004 16:21:42 -0800" or
       "2004-02-29 16:21:42" or even "next Thursday".  A date string may contain items indicating calendar  date,  time  of  day,
       time  zone,  day  of week, relative time, relative date, and numbers.  An empty string indicates the beginning of the day.
       The date string format is more complex than is easily documented here but is fully described in the info documentation.