哪个PHP函数可以返回当前日期/时间?


您可以使用$_SERVER['REQUEST_TIME']变量(自PHP 5.1.0起可用)或time()函数来获取当前的Unix时间戳。


PHP的time()返回当前Unix时间戳。这样,您就可以使用date()函数将其格式化为您需要的格式。

$date = date('Format String', time());

正如Paolo在评论中提到的,第二个论点是多余的。下面的代码段相当于上面的代码段:

$date = date('Format String');

你可以使用$_SERVER['REQUEST_TIME']变量或time()函数。这两个函数都返回Unix时间戳。

大多数情况下,这两个解决方案将产生完全相同的Unix时间戳。它们之间的区别是$_SERVER['REQUEST_TIME']返回最近服务器请求的时间戳,而time()返回当前时间。根据应用程序的不同,这可能会在准确性上产生微小的差异,但在大多数情况下,这两种解决方案都足够了。

根据上面的示例代码,一旦获得Unix时间戳,您将希望格式化此信息。未格式化的Unix时间看起来像:1232659628

因此,为了得到一些可以工作的东西,您可以使用date()函数来格式化它。

关于date()函数的使用方法,PHP手册中有很好的参考资料。

例如,下面的代码返回一个日期:01/22/2009 04:35:00 pm:

echo date("m/d/Y h:i:s a", time());

Use:

$date = date('m/d/Y h:i:s a', time());

它的工作原理。


时间会随着服务器时间流逝。一个简单的解决方法是在调用date()或time()函数之前使用date_default_timezone_set手动设置时区。

我在澳大利亚墨尔本,所以我有这样的东西:

date_default_timezone_set('Australia/Melbourne');

或者另一个例子是洛杉矶-美国:

date_default_timezone_set('America/Los_Angeles');

你还可以通过以下命令查看服务器当前所在的时区:

date_default_timezone_get();

比如:

$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;

所以你问题的简短答案是:

// Change the line below to your timezone!
date_default_timezone_set('Australia/Melbourne');
$date = date('m/d/Y h:i:s a', time());

那么所有的时间都将是你刚刚设置的时区:)


// Simply:
$date = date('Y-m-d H:i:s');

// Or:
$date = date('Y/m/d H:i:s');

// This would return the date in the following formats respectively:
$date = '2012-03-06 17:33:07';
// Or
$date = '2012/03/06 17:33:07';

/** 
 * This time is based on the default server time zone.
 * If you want the date in a different time zone,
 * say if you come from Nairobi, Kenya like I do, you can set
 * the time zone to Nairobi as shown below.
 */

date_default_timezone_set('Africa/Nairobi');

// Then call the date functions
$date = date('Y-m-d H:i:s');
// Or
$date = date('Y/m/d H:i:s');

// date_default_timezone_set() function is however
// supported by PHP version 5.1.0 or above.

有关时区参考,请参见支持的时区列表。


我发现在PHP中获取当前时间的最简单方法是这样的。

//Prints out something like 10:00am Just be sure to set your timezone correctly.
date_default_timezone_set("America/Chicago");
$TIME = date('G:ia'); 

<?php
echo "<b>".date('l\, F jS\, Y ')."</b>";
?>

像这样的指纹

2012年12月9日,星期天


从PHP 5.2.0开始,你可以使用DateTime()类:

use \Datetime;

$now = new DateTime();
echo $now->format('Y-m-d H:i:s');    // MySQL datetime format
echo $now->getTimestamp();           // Unix Timestamp -- Since PHP 5.3

并指定时区:

$now = new DateTime(null, new DateTimeZone('America/New_York'));
$now->setTimezone(new DateTimeZone('Europe/London'));    // Another way
echo $now->getTimezone();

 $date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
 echo $date->format('d-m-Y H:i:s');

更新

 //Also get am/pm in datetime:
 echo $date->format('d-m-Y H:i:s a'); // output 30-12-2013 10:16:15 am

对于日期格式,PHP date() Function很有用。


参考:这里有一个链接

由于使用夏令时,这比简单地在时间戳中添加或减去一天或一个月中的秒数更可靠。

PHP代码

// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)

根据如何使用PHP获取当前日期时间(NOW)这篇文章,有两种常见的方法来获取当前日期。要在PHP中获取当前的日期时间(now),您可以在任何PHP版本中使用date类,或者在PHP >= 5.2中使用datetime类。

这里有各种日期格式表达式。

使用日期的示例

该表达式将以Y-m-d H:i:s格式返回NOW。

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

使用datetime类的示例

该表达式将以Y-m-d H:i:s格式返回NOW。

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

如果您想要不同的时间刻度,请使用:

$tomorrow  = mktime(0, 0, 0, date("m")  , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"),   date("Y"));
$nextyear  = mktime(0, 0, 0, date("m"),   date("d"),   date("Y")+1);

date_default_timezone_set("Asia/Calcutta");
echo date("Y/m/d H:i:s");

设置时区:

date_default_timezone_set('Asia/Calcutta');

然后调用日期函数

$date = date('Y-m-d H:i:s');

date_default_timezone_set('Europe/Warsaw');
echo("<p class='time'>".date('H:i:s')."</p>");
echo("<p class='date'>".date('d/m/Y')."</p>");

PHP的date函数可以完成这项工作。

日期()

描述:

string date(string $format [, int $timestamp = time()])

返回根据给定格式字符串使用给定整数时间戳格式化的字符串,如果没有给出时间戳则返回当前时间。

例子:

$today = date("F j, Y, g:i a");               // March 10, 2001, 5:16 pm
$today = date("m.d.y");                       // 03.10.01
$today = date("j, n, Y");                     // 10, 3, 2001
$today = date("Ymd");                         // 20010310
$today = date('h-i-s, j-m-y, it is w Day');   // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y");             // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');   // 17:03:18 m is month
$today = date("H:i:s");                       // 17:16:18
$today = date("Y-m-d H:i:s");                 // 2001-03-10 17:16:18 (the MySQL DATETIME format)

// Set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2016 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2016 is on a Saturday
echo "July 1, 2016 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2016));

/* Use the constants in the format parameter */
// Prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// Prints something like: 2016-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));

如果你想获得日期,如12-3-2016,分开每一天,月和年的值,然后复制粘贴以下代码:

$day = date("d");
$month = date("m");
$year = date("y");
print "date" . $day . "-" . $month . "-" . $year;

date(format, timestamp)

date函数返回一个根据给定格式字符串使用给定整数时间戳格式化的字符串,如果没有给出时间戳则返回当前时间。换句话说,timestamp是可选的,默认值为time()。

参数为-

format -必选。指定时间戳格式 timestamp -时间戳(可选)。默认为当前日期和时间

如何获得一次简单的约会

date()函数所需的format参数指定如何格式化日期(或时间)。

下面是一些常用来表示日期的字符:

d -表示一个月中的第一天(01 ~ 31) m -代表一个月(01 ~ 12) Y -年份(四位数) l(小写“l”)-代表星期几

还可以在字符之间插入其他字符,如“/”、“。”或“-”,以添加额外的格式。

下面的例子用三种不同的方式格式化今天的日期:

<?php
    echo "Today is " . date("Y/m/d") . "<br>";
    echo "Today is " . date("Y.m.d") . "<br>";
    echo "Today is " . date("Y-m-d") . "<br>";
    echo "Today is " . date("l");
?>

一些有用的链接

gmdate() -格式化a 格林尼治时间/ UTC日期/时间 idate() -格式化a 本地时间/日期为整数 getdate() -获取 日期/时间信息 getlastmod () - 获取最后一页修改的时间 mktime() -获取Unix 日期的时间戳 strftime() -格式 根据区域设置的本地时间/日期 time() -返回电流 Unix时间戳 strtotime () 解析任何英文文本日期时间描述到Unix 时间戳 预定义的DateTime 常量


你也可以使用这种格式:

$date = date("d-m-Y");

Or

$date = date("Y-m-d H:i:s");

PHP以秒为单位返回当前时间。你需要把它们格式化成你想要的任何格式。

<?php
    // time() returns current time in seconds
    $in_seconds = time();

    // strftime - Format a local time/date according to locale settings
    echo strftime("%m/%d/%y", $in_seconds);
?>

参考:http://php.net/manual/en/function.strftime.php


<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today = date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today = date("m.d.y");                         // 03.10.01
$today = date("j, n, Y");                       // 10, 3, 2001
$today = date("Ymd");                           // 20010310
$today = date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today = date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today = date("H:i:s");                         // 17:16:18
$today = date("Y-m-d H:i:s");                   // 2001-03-10 17:16:18 (the MySQL DATETIME format)
?>

另一种简单的方法是获取当前日期和时间的时间戳。使用mktime()函数:

$now = mktime(); // Return timestamp of the current time

然后您可以将其转换为另一种日期格式:

//// Prints something like: Thursday 26th of January 2017 01:12:36 PM
echo date('l jS \of F Y h:i:s A',$now);

更多的日期格式在这里: http://php.net/manual/en/function.date.php


如果你是孟加拉国人,如果你想知道达卡的时间,那么用这个:

$date = new DateTime();
$date->setTimeZone(new DateTimeZone("Asia/Dhaka"));
$get_datetime = $date->format('d.m.Y H:i:s');

非常简单 echo $date = date('Y-m-d H:i:s');


echo date("d-m-Y H:i:sa");

这段代码将获得运行该代码的服务器的日期和时间。


日期格式也取决于:

echo date("d/m/Y H:i:sa"); // 13/04/2017 19:38:15pm

你可以使用下面的代码:

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

下面是一些常用的表示时间的字符:

H -以前导零表示的12小时格式(01到12) i -前导0的分钟(00到59) s -前导0的秒(00到59) a -小写的子午线前后(am或pm)

确定你的时区

<?php
    date_default_timezone_set("America/New_York");
    echo "The time is " . date("h:i:sa");
?>

看看这个(可选)

<?php
    $d = mktime(11, 14, 54, 8, 12, 2014);
    echo "Created date is " . date("Y-m-d h:i:sa", $d);
?>

为日期

<?php
    echo "Today is " . date("Y/m/d") . ;
    echo "Today is " . date("Y.m.d") . ;
    echo "Today is " . date("Y-m-d") . ;
    echo "Today is " . date("l");
?>

下面是一些常用来表示日期的字符:

d -表示一个月中的第一天(01 ~ 31) m -代表一个月(01 ~ 12) Y -年份(四位数) l(小写“l”)-代表星期几

Source-W3-Schools


我们可以使用date函数设置默认时区:

<?php
    date_default_timezone_set("Asia/Kolkata");
    echo "Today is " . date("Y/m/d") . "<br>";
    echo "Today is " . date("Y.m.d") . "<br>";
    echo "Today is " . date("Y-m-d") . "<br>";
    echo "Today is " . date("l");
    echo "The time is " . date("h:i:sa");
?>

获取当前时间和日期的最佳方法是使用PHP中的date函数:

$date = date('FORMAT'); // FORMAT E.g.: Y-m-d H:i:s

$current_date = date('Y-m-d H:i:s');

使用Unix时间戳:

$now_date = date('FORMAT', time()); // FORMAT Eg : Y-m-d H:i:s

设置服务器时区。

date_default_timezone_set('Asia/Calcutta');

这里有一个不同的时区列表。


Linux服务器时间与PHP time()时区差异如下:

<?php
    putenv("TZ=Asia/Kabul");
    $t = time();
    echo date('d/m/Y H:i:sa', $t);
?>

通常,date的这个函数对每个人都有用:date("Y/m/d");

但是时间是不同的,因为时间函数取决于PHP版本或系统日期。

所以可以像这样使用它来获得我们自己的时区:

$date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
echo $date->format('H:m:s');

这个函数显示24小时时间。


echo date('y-m-d'); // Today

这将返回今天的日期。


非常简单的

date_default_timezone_set('Asia/Kolkata');
$date = date('m/d/Y H:i:s', time());

对于新的PHP程序员来说,他们可能会困惑为什么有这么多方法来获取当前日期和时间,以及在他们的项目中使用哪一种方法。

1. date方法(PHP 4, PHP 5, PHP 7)

这是php中获取日期和时间的最常见和最简单的方法。

// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');


// Prints something like: Monday
echo date("l");

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));

/* use the constants in the format parameter */
// prints something like: Wed, 25 Sep 2013 15:28:57 -0700
echo date(DATE_RFC2822);

// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));

你可以在这里了解更多

2. DateTime类(PHP 5 >= 5.2.0, PHP 7)

当你想在OOP中使用PHP时,这是获取日期和时间的最佳方式。

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";

// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";

// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";

// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

你可以在这里了解更多

3.碳日期时间套餐

如果你正在使用Composer, Laravel, Symfony或任何类型的框架,这是获得日期和时间的最佳方式。此外,这个包扩展了php中的DateTime类,因此您可以使用DateTime类中的所有方法。 这个内置的框架像laravel,所以你不需要单独安装它。

printf("Right now is %s", Carbon::now()->toDateTimeString());
printf("Right now in Vancouver is %s", Carbon::now('America/Vancouver')); // automatically converted to string
$tomorrow = Carbon::now()->addDay();
$lastWeek = Carbon::now()->subWeek();

// Carbon embed 823 languages:
echo $tomorrow->locale('fr')->isoFormat('dddd, MMMM Do YYYY, h:mm');
echo $tomorrow->locale('ar')->isoFormat('dddd, MMMM Do YYYY, h:mm');

$officialDate = Carbon::now()->toRfc2822String();

$howOldAmI = Carbon::createFromDate(1975, 5, 21)->age;

$noonTodayLondonTime = Carbon::createFromTime(12, 0, 0, 'Europe/London');

$internetWillBlowUpOn = Carbon::create(2038, 01, 19, 3, 14, 7, 'GMT');

if (Carbon::now()->isWeekend()) {
    echo 'Party!';
}
echo Carbon::now()->subMinutes(2)->diffForHumans(); // '2 minutes ago'

你可以在这里了解更多

希望这对你有所帮助,如果你知道任何其他获取日期和时间的方法,请随意编辑答案。


您可以简单地使用这段代码来获取当前日期和时间

echo date('r', time());

简单地使用:date(“Y-m-d H:i:s”),这会给你你的日期和时间,比如“2020-08-22 12:20:30”。 在date()函数之前添加date_default_timezone_set("your timezone ")来获取你所在区域/区域的时间日期。 在这里你可以找到你所在的时区


下面是一些常用的表示时间的字符:

d -表示一个月中的第一天(01 ~ 31) m -代表一个月(01 ~ 12) Y -年份(四位数) l(小写“l”)-代表星期几 H -以小时为单位的24小时格式(00至23) H -以前导零表示的12小时格式(01到12) i -前导0的分钟(00到59) s -前导0的秒(00到59) a -小写的子午线前后(am或pm)

例子:

echo "Today " . date("Y/m/d") ;
echo "time " . date("h:i:sa");

您的国家时区:支持的时区列表

date_default_timezone_set('Asia/Kolkata');

$dateYmd = date('Y-m-d');
echo "Current Year Month Day: $dateYmd";

本年月日:2022-01-03

$datehms = date('h:i:s');
echo "Current Hour Minute Second: $datehms";

当前小时分秒:11:05:38


你可以:

$now = strtotime(date('Y-m-d H:i:s')); // = Now 

完整的格式选项请参见文档:https://www.php.net/manual/en/function.date.php


使用date()和DateTimeInterface::format格式化日期,即date('Y-m-d H:i:s');,你有这些可选格式:

来源:DateTimeInterface:::格式页面。

format character Description Example returned values
Day --- ---
d Day of the month, 2 digits with leading zeros 01 to 31
D A textual representation of a day, three letters Mon through Sun
j Day of the month without leading zeros 1 to 31
l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday
N ISO 8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
z The day of the year (starting from 0) 0 through 365
Week --- ---
W ISO 8601 week number of year, weeks starting on Monday Example: 42 (the 42nd week in the year)
Month --- ---
F A full textual representation of a month, such as January or March January through December
m Numeric representation of a month, with leading zeros 01 through 12
M A short textual representation of a month, three letters Jan through Dec
n Numeric representation of a month, without leading zeros 1 through 12
t Number of days in the given month 28 through 31
Year --- ---
L Whether it's a leap year 1 if it is a leap year, 0 otherwise.
o ISO 8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. Examples: 1999 or 2003
X An expanded full numeric representation of a year, at least 4 digits, with - for years BCE, and + for years CE. Examples: -0055, +0787, +1999, +10191
x An expanded full numeric representation if requried, or a standard full numeral representation if possible (like Y). At least four digits. Years BCE are prefixed with a -. Years beyond (and including) 10000 are prefixed by a +. Examples: -0055, 0787, 1999, +10191
Y A full numeric representation of a year, at least 4 digits, with - for years BCE. Examples: -0055, 0787, 1999, 2003, 10191
y A two digit representation of a year Examples: 99 or 03
Time --- ---
a Lowercase Ante meridiem and Post meridiem am or pm
A Uppercase Ante meridiem and Post meridiem AM or PM
B Swatch Internet time 000 through 999
g 12-hour format of an hour without leading zeros 1 through 12
G 24-hour format of an hour without leading zeros 0 through 23
h 12-hour format of an hour with leading zeros 01 through 12
H 24-hour format of an hour with leading zeros 00 through 23
i Minutes with leading zeros 00 to 59
s Seconds with leading zeros 00 through 59
u Microseconds. Note that date() will always generate 000000 since it takes an int parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. Example: 654321
v Milliseconds. Same note applies as for u. Example: 654
Timezone --- ---
e Timezone identifier Examples: UTC, GMT, Atlantic/Azores
I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise.
O Difference to Greenwich time (GMT) without colon between hours and minutes Example: +0200
P Difference to Greenwich time (GMT) with colon between hours and minutes Example: +02:00
p The same as P, but returns Z instead of +00:00 (available as of PHP 8.0.0) Examples: Z or +02:00
T Timezone abbreviation, if known; otherwise the GMT offset. Examples: EST, MDT, +05
Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400
Full Date/Time --- ---
c ISO 8601 date 2004-02-12T15:19:21+00:00
r » RFC 2822/» RFC 5322 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200
U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time()