zoukankan      html  css  js  c++  java
  • PHP 中获取当前时间[Datetime Now]

    在 PHP 中可以通过date()获取当前时间,在>5.2的版本中最好还是用 datetime 类型

    date()

    <?php
    echo date('Y-m-d H:i:s');
    ?>
    

    DateTime

    <?php
    $dt = new DateTime();
    echo $dt->format('Y-m-d H:i:s');
    ?>
    

    更完善的方法

    上面两个例子返回的当前时间都是服务器时区时间(timezone 可在php.ini中声明)
    Above examples will return NOW using your server timezone, as it is defined in php.ini, for example:

    [Date]
    ; Defines the default timezone used by the date functions
    ; http://php.net/date.timezone
    date.timezone = Europe/Athens
    

    最准确的方法是以UTC时间,所以

    /* server timezone */
    define('CONST_SERVER_TIMEZONE', 'UTC');
     
    /* server dateformat */
    define('CONST_SERVER_DATEFORMAT', 'YmdHis');
    
    <?php
    /**
     * Converts current time for given timezone (considering DST)
     *  to 14-digit UTC timestamp (YYYYMMDDHHMMSS)
     *
     * DateTime requires PHP >= 5.2
     *
     * @param $str_user_timezone
     * @param string $str_server_timezone
     * @param string $str_server_dateformat
     * @return string
     */
    function now($str_user_timezone,
           $str_server_timezone = CONST_SERVER_TIMEZONE,
           $str_server_dateformat = CONST_SERVER_DATEFORMAT) {
     
      // set timezone to user timezone
      date_default_timezone_set($str_user_timezone);
     
      $date = new DateTime('now');
      $date->setTimezone(new DateTimeZone($str_server_timezone));
      $str_server_now = $date->format($str_server_dateformat);
     
      // return timezone to server default
      date_default_timezone_set($str_server_timezone);
     
      return $str_server_now;
    }
    ?>
    

    原文 : http://www.pontikis.net/tip/?id=18

  • 相关阅读:
    事务
    handler
    codeforces 27E Number With The Given Amount Of Divisors
    暑期实践日志(五)
    暑期实践日志(四)
    暑期实践日志(三)
    暑期实践日志(二)
    暑期实践日志(一)
    数论 UVALive 2756
    数论 UVALive 2911
  • 原文地址:https://www.cnblogs.com/flowerszhong/p/5313794.html
Copyright © 2011-2022 走看看