PHP 时间类 Carbon 中文手册

783 阅读15分钟

包说明

DateTime的API扩展,支持281种不同的语言

安装

默认laravel 已经安装 ,文件所在路径:/vendor/nesbot

composer require nesbot/carbon

使用手册

创建实例化

$carbon = new Carbon();                  // equivalent to Carbon::now()
$carbon = new Carbon('时间', '时区');
Carbon::createFromFormat($format, $time, $tz);
echo Carbon::createFromDate($year, $month, $day, $tz)."\n";
echo Carbon::createMidnightDate($year, $month, $day, $tz)."\n";
echo Carbon::createFromTime($hour, $minute, $second, $tz)."\n";
echo Carbon::createFromTimeString("$hour:$minute:$second", $tz)."\n";
echo Carbon::create($year, $month, $day, $hour, $minute, $second, $tz)."\n";
 Carbon::parse('first day of December 2008')->addWeeks(2)

当前时间now($tz = null)

参数设置时区,默认跟谁你的PHP设置或者是自定义设置

echo Carbon::now();
        echo Carbon::now('Asia/Jayapura');

明天,昨天

Carbon::tomorrow();
Carbon::yesterday();

时间 加多少天,多少秒,多少小时等

$mutable = Carbon::now();
$data=[];
$data[]='现在:'.$mutable->add('minute','1');
$data[]='时间+ 1 分钟:'.$mutable->add('minute','1');
$data[]='时间+10秒:'.$mutable->add('second','10');
$data[]='时间+ 1 小时:'.$mutable->add('hour','1');
$data[]='时间+ 1 天:'.$mutable->add('day','1');
$data[]='时间+ 1 周:'.$mutable->add('week','1');
$data[]='时间+ 1 月:'.$mutable->add('month','1');
$data[]='时间+ 1 年:'.$mutable->add('year','1');
现在:2020-07-29 15:41:43
时间+ 1 分钟:2020-07-29 15:42:43
时间+10秒:2020-07-29 15:42:53
时间+ 1 小时:2020-07-29 16:42:53
时间+ 1 天:2020-07-30 16:42:53
时间+ 1 周:2020-08-06 16:42:53
时间+ 1 月:2020-09-06 16:42:53
时间+ 1 年:2021-09-06 16:42:53

时间减多少天,秒,时,周,月,年等

$data[]='现在:'.$mutable->sub('minute','1');
$data[]='时间- 1 分钟:'.$mutable->sub('minute','1');
$data[]='时间-10秒:'.$mutable->sub('second','10');
$data[]='时间- 1 小时:'.$mutable->sub('hour','1');
$data[]='时间- 1 天:'.$mutable->sub('day','1');
$data[]='时间- 1 周:'.$mutable->sub('week','1');
$data[]='时间- 1 月:'.$mutable->sub('month','1');
$data[]='时间- 1 年:'.$mutable->sub('year','1');
现在:2020-07-29 15:48:14
时间- 1 分钟:2020-07-29 15:47:14
时间-10秒:2020-07-29 15:47:04
时间- 1 小时:2020-07-29 14:47:04
时间- 1 天:2020-07-28 14:47:04
时间- 1 周:2020-07-21 14:47:04
时间- 1 月:2020-06-21 14:47:04
时间- 1 年:2019-06-21 14:47:04

当前日期 today($tz = null)

日期增减addDay()

后面参数支持正数和负数,负数今天日期减多少天,加,今天日期加多少天

默认是明天,今天是28号

 $tomorrow = Carbon::now()->addDay();
echo ($tomorrow);
//2020-07-29 11:01:03

 $tomorrow = Carbon::now()->addDay(-7);
echo ($tomorrow);
//2020-07-21 11:01:24

比较2个日期相差

$dtToronto = Carbon::create(2012, 1, 1, 0, 0, 0);
$dtVancouver = Carbon::create(2013, 4, 12, 6, 4, 6);
$data[]='相差小时:'. $dtVancouver->diffInHours($dtToronto);
$data[]='相差天:'. $dtVancouver->diffInDays($dtToronto);
$data[]='相差分:'. $dtVancouver->diffInMinutes($dtToronto);
$data[]='相差秒:'. $dtVancouver->diffInSeconds($dtToronto);
$data[]='相差周:'. $dtVancouver->diffInWeeks($dtToronto);
$data[]='相差月:'. $dtVancouver->diffInMonths($dtToronto);
$data[]='相差年:'. $dtVancouver->diffInYears($dtToronto);
相差小时:11214
相差天:467
相差分:672844
相差秒:40370646
相差周:66
相差月:15
相差年:1

本地化

设置翻译规则

 $boringLanguage = 'zh';
$translator = \Carbon\Translator::get($boringLanguage);
$translator->setTranslations([
   'day' => ':count 天哦|:count 天了',
]);

$date1 = Carbon::create(2018, 1, 1, 0, 0, 0);
$date2 = Carbon::create(2018, 1, 4, 4, 0, 0);

echo $date1->locale('zh')->diffForHumans($date2); //3 天哦前

设置语言locale,具体语言查看 vendor/nesbot/carbon/src/Carbon/Lang 目录下

locale 支持多个查找语言

\Carbon\Translator::get('xx')->setTranslations([
    'day' => ':count Xday',
]);
\Carbon\Translator::get('xy')->setTranslations([
    'day' => ':count Yday',
    'hour' => ':count Yhour',
]);

$date = Carbon::now()->locale('xx', 'xy', 'es')->sub('3 days 6 hours 40 minutes');

echo $date->ago(['parts' => 3]); // hace 3 Xday 6 Yhour 40 minutos

首先先查找 xx 语言,然后匹配不到查找xy,最后查找es

查看支持的语言

Carbon::getAvailableLocales()

黑白课堂

本地化相关辅助方法

$zhTwInfo = Carbon::getAvailableLocalesInfo()['zh_TW'];
$srCyrlInfo = Carbon::getAvailableLocalesInfo()['sr_Cyrl'];
$caInfo = Carbon::getAvailableLocalesInfo()['ca'];

var_dump($zhTwInfo->getId());                      // string(5) "zh_TW"
var_dump($zhTwInfo->getNames());                  
/*
array(2) {
  ["isoName"]=>
  string(7) "Chinese"
  ["nativeName"]=>
  string(38) "中文 (Zhōngwén), 汉语, 漢語"
}
*/
var_dump($zhTwInfo->getCode());                    // string(2) "zh"
var_dump($zhTwInfo->getVariant());                 // NULL
var_dump($srCyrlInfo->getVariant());               // string(4) "Cyrl"
var_dump($zhTwInfo->getVariantName());             // NULL
var_dump($srCyrlInfo->getVariantName());           // string(8) "Cyrillic"
var_dump($zhTwInfo->getRegion());                  // string(2) "TW"
var_dump($srCyrlInfo->getRegion());                // NULL
var_dump($zhTwInfo->getRegionName());              // string(25) "Taiwan, Province of China"
var_dump($srCyrlInfo->getRegionName());            // NULL
var_dump($zhTwInfo->getFullIsoName());             // string(7) "Chinese"
var_dump($caInfo->getFullIsoName());               // string(18) "Catalan, Valencian"
var_dump($zhTwInfo->getFullNativeName());          // string(38) "中文 (Zhōngwén), 汉语, 漢語"
var_dump($caInfo->getFullNativeName());            // string(18) "català, valencià"
var_dump($zhTwInfo->getIsoName());                 // string(7) "Chinese"
var_dump($caInfo->getIsoName());                   // string(7) "Catalan"
var_dump($zhTwInfo->getNativeName());              // string(20) "中文 (Zhōngwén)"
var_dump($caInfo->getNativeName());                // string(7) "català"
var_dump($zhTwInfo->getIsoDescription());          // string(35) "Chinese (Taiwan, Province of China)"
var_dump($srCyrlInfo->getIsoDescription());        // string(18) "Serbian (Cyrillic)"
var_dump($caInfo->getIsoDescription());            // string(7) "Catalan"
var_dump($zhTwInfo->getNativeDescription());       // string(48) "中文 (Zhōngwén) (Taiwan, Province of China)"
var_dump($srCyrlInfo->getNativeDescription());     // string(34) "српски језик (Cyrillic)"
var_dump($caInfo->getNativeDescription());         // string(7) "català"
var_dump($zhTwInfo->getFullIsoDescription());      // string(35) "Chinese (Taiwan, Province of China)"
var_dump($srCyrlInfo->getFullIsoDescription());    // string(18) "Serbian (Cyrillic)"
var_dump($caInfo->getFullIsoDescription());        // string(18) "Catalan, Valencian"
var_dump($zhTwInfo->getFullNativeDescription());   // string(66) "中文 (Zhōngwén), 汉语, 漢語 (Taiwan, Province of China)"
var_dump($srCyrlInfo->getFullNativeDescription()); // string(34) "српски језик (Cyrillic)"
var_dump($caInfo->getFullNativeDescription());     // string(18) "català, valencià"

$srCyrlInfo->setIsoName('foo, bar')->setNativeName('biz, baz');
var_dump($srCyrlInfo->getIsoName());               // string(3) "foo"
var_dump($srCyrlInfo->getFullIsoName());           // string(8) "foo, bar"
var_dump($srCyrlInfo->getFullIsoDescription());    // string(19) "foo, bar (Cyrillic)"
var_dump($srCyrlInfo->getNativeName());            // string(3) "biz"
var_dump($srCyrlInfo->getFullNativeName());        // string(8) "biz, baz"
var_dump($srCyrlInfo->getFullNativeDescription()); // string(19) "biz, baz (Cyrillic)"

// You can also access directly regions/languages lists:
var_dump(\Carbon\Language::all()['zh']);          
/*
array(2) {
  ["isoName"]=>
  string(7) "Chinese"
  ["nativeName"]=>
  string(38) "中文 (Zhōngwén), 汉语, 漢語"
}
*/
var_dump(\Carbon\Language::regions()['TW']);      
/*
string(25) "Taiwan, Province of China"
*/

全局设置语言

Carbon::setLocale("zh");

isoFormat 对日期名称和月份名称使用上下文化的方法

$date = Carbon::parse('2018-06-15 17:34:15.984512', 'UTC');
echo $date->isoFormat('MMMM Do YYYY, h:mm:ss a'); // June 15th 2018, 5:34:15 pm
echo "\n";
echo $date->isoFormat('dddd');           // Friday
echo "\n";
echo $date->isoFormat('MMM Do YY');      // Jun 15th 18
echo "\n";
echo $date->isoFormat('YYYY [escaped] YYYY'); // 2018 escaped 2018
CodeExampleDescription
OD5Day number with alternative numbers such as 三 for 3 if locale is ja_JP
OM1Month number with alternative numbers such as ၀၂ for 2 if locale is my_MM
OY2017Year number with alternative numbers such as ۱۹۹۸ for 1998 if locale is fa
OH1724-hours number with alternative numbers such as ႑႓ for 13 if locale is shn_MM
Oh512-hours number with alternative numbers such as 十一 for 11 if locale is lzh_TW
Om4Minute number with alternative numbers such as ୫୭ for 57 if locale is or
Os5Second number with alternative numbers such as 十五 for 15 if locale is ja_JP
D5Day of month number (from 1 to 31)
DD05Day of month number with trailing zero (from 01 to 31)
Do5thDay of month with ordinal suffix (from 1st to 31th), translatable
d4Day of week number (from 0 (Sunday) to 6 (Saturday))
ddThMinified day name (from Su to Sa), transatable
dddThuShort day name (from Sun to Sat), transatable
ddddThursdayDay name (from Sunday to Saturday), transatable
DDD5Day of year number (from 1 to 366)
DDDD005Day of year number with trailing zeros (3 digits, from 001 to 366)
DDDo5thDay of year number with ordinal suffix (from 1st to 366th), translatable
e4Day of week number (from 0 (Sunday) to 6 (Saturday)), similar to "d" but this one is translatable (takes first day of week of the current locale)
E4Day of week number (from 1 (Monday) to 7 (Sunday))
H17Hour from 0 to 23
HH17Hour with trailing zero from 00 to 23
h5Hour from 0 to 12
hh05Hour with trailing zero from 00 to 12
k17Hour from 1 to 24
kk17Hour with trailing zero from 01 to 24
m4Minute from 0 to 59
mm04Minute with trailing zero from 00 to 59
apmMeridiem am/pm
APMMeridiem AM/PM
s5Second from 0 to 59
ss05Second with trailing zero from 00 to 59
S0Second tenth
SS08Second hundredth (on 2 digits with trailing zero)
SSS084Millisecond (on 3 digits with trailing zeros)
SSSS0845Second ten thousandth (on 4 digits with trailing zeros)
SSSSS08451Second hundred thousandth (on 5 digits with trailing zeros)
SSSSSS084512Microsecond (on 6 digits with trailing zeros)
SSSSSSS0845120Second ten millionth (on 7 digits with trailing zeros)
SSSSSSSS08451200Second hundred millionth (on 8 digits with trailing zeros)
SSSSSSSSS084512000Nanosecond (on 9 digits with trailing zeros)
M1Month from 1 to 12
MM01Month with trailing zero from 01 to 12
MMMJanShort month name, translatable
MMMMJanuaryMonth name, translatable
Mo1stMonth with ordinal suffix from 1st to 12th, translatable
Q1Quarter from 1 to 4
Qo1stQuarter with ordinal suffix from 1st to 4th, translatable
G2017ISO week year (see ISO week date)
GG2017ISO week year (on 2 digits with trailing zero)
GGG2017ISO week year (on 3 digits with trailing zeros)
GGGG2017ISO week year (on 4 digits with trailing zeros)
GGGGG02017ISO week year (on 5 digits with trailing zeros)
g2017Week year according to locale settings, translatable
gg2017Week year according to locale settings (on 2 digits with trailing zero), translatable
ggg2017Week year according to locale settings (on 3 digits with trailing zeros), translatable
gggg2017Week year according to locale settings (on 4 digits with trailing zeros), translatable
ggggg02017Week year according to locale settings (on 5 digits with trailing zeros), translatable
W1ISO week number in the year (see ISO week date)
WW01ISO week number in the year (on 2 digits with trailing zero)
Wo1stISO week number in the year with ordinal suffix, translatable
w1Week number in the year according to locale settings, translatable
ww01Week number in the year according to locale settings (on 2 digits with trailing zero)
wo1stWeek number in the year according to locale settings with ordinal suffix, translatable
x1483635845085Millisecond-precision timestamp (same as date.getTime() in JavaScript)
X1483635845Timestamp (number of seconds since 1970-01-01)
Y2017Full year from -9999 to 9999
YY17Year on 2 digits from 00 to 99
YYYY2017Year on 4 digits from 0000 to 9999
YYYYY02017Year on 5 digits from 00000 to 09999
YYYYYY+002017Year on 5 digits with sign from -09999 to +09999
zUTCAbbreviated time zone name
zzUTCTime zone name
Z+00:00Time zone offset HH:mm
ZZ+0000Time zone offset HHmm

calendar 显示日历日期

$date = CarbonImmutable::now();
$data[]= $date->locale('zh')->calendar();
$data[]=$date->sub('1 day 3 hour')->calendar();
 $data[]=$date->add('1 day 3 hour')->calendar();
今天16:51
昨天13:51
明天19:51

parse 根据字符串创建时间实例

$date = CarbonImmutable::parse('2020-06-29 16:55:0');
echo $date;

format() 格式化

www.php.net/manual/en/d…

 echo $date->locale('zh')->format('Y-m-d H:i:s');   

可直接使用取得属性输出值

$dt = Carbon::parse('2012-10-5 23:26:11.123789');

// These getters specifically return integers, ie intval()
var_dump($dt->year);                                         // int(2012)
var_dump($dt->month);                                        // int(10)
var_dump($dt->day);                                          // int(5)
var_dump($dt->hour);                                         // int(23)
var_dump($dt->minute);                                       // int(26)
var_dump($dt->second);                                       // int(11)
var_dump($dt->micro);                                        // int(123789)
// dayOfWeek returns a number between 0 (sunday) and 6 (saturday)
var_dump($dt->dayOfWeek);                                    // int(5)
// dayOfWeekIso returns a number between 1 (monday) and 7 (sunday)
var_dump($dt->dayOfWeekIso);                                 // int(5)
var_dump($dt->englishDayOfWeek);                             // string(6) "Friday"
var_dump($dt->shortEnglishDayOfWeek);                        // string(3) "Fri"
var_dump($dt->locale('de')->dayName);                        // string(7) "Freitag"
var_dump($dt->locale('de')->shortDayName);                   // string(3) "Fr."
var_dump($dt->locale('de')->minDayName);                     // string(2) "Fr"
var_dump($dt->englishMonth);                                 // string(7) "October"
var_dump($dt->shortEnglishMonth);                            // string(3) "Oct"
var_dump($dt->locale('de')->monthName);                      // string(7) "Oktober"
var_dump($dt->locale('de')->shortMonthName);                 // string(3) "Okt"

// Following are deprecated, locale* and shortLocale* properties
// are translated using formatLocalized() based on LC_TIME language.
setlocale(LC_TIME, 'German');
var_dump($dt->localeDayOfWeek);                              // string(7) "Freitag"
var_dump($dt->shortLocaleDayOfWeek);                         // string(2) "Fr"
var_dump($dt->localeMonth);                                  // string(7) "Oktober"
var_dump($dt->shortLocaleMonth);                             // string(3) "Okt"
setlocale(LC_TIME, '');

var_dump($dt->dayOfYear);                                    // int(279)
var_dump($dt->weekNumberInMonth);                            // int(1)
// weekNumberInMonth consider weeks from monday to sunday, so the week 1 will
// contain 1 day if the month start with a sunday, and up to 7 if it starts with a monday
var_dump($dt->weekOfMonth);                                  // int(1)
// weekOfMonth will returns 1 for the 7 first days of the month, then 2 from the 8th to
// the 14th, 3 from the 15th to the 21st, 4 from 22nd to 28th and 5 above
var_dump($dt->weekOfYear);                                   // int(40)
var_dump($dt->daysInMonth);                                  // int(31)
var_dump($dt->timestamp);                                    // int(1349479571)
// Millisecond-precise timestamp (useful to pass it to JavaScript)
var_dump($dt->valueOf());                                    // float(1349479571124)
// Custom-precision timestamp
var_dump($dt->getPreciseTimestamp(6));                       // float(1.3494795711238E+15)
var_dump(Carbon::createFromDate(1975, 5, 21)->age);          // int(45) calculated vs now in the same tz
var_dump($dt->quarter);                                      // int(4)

// Returns an int of seconds difference from UTC (+/- sign included)
var_dump(Carbon::createFromTimestampUTC(0)->offset);         // int(0)
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->offset);                // int(3600)
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->getOffset());           // int(3600)

// Returns an int of hours difference from UTC (+/- sign included)
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->offsetMinutes);         // int(60)
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->offsetHours);           // int(1)

// Returns timezone offset as string
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->getOffsetString());     // string(6) "+01:00"

// Returns timezone as CarbonTimeZone
var_dump(Carbon::createFromTimestamp(0, 'Europe/Paris')->getTimezone());
/* object(Carbon\CarbonTimeZone)#3497 (2) {
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(12) "Europe/Paris"
} */

// Indicates if day light savings time is on
var_dump(Carbon::createFromDate(2012, 1, 1)->dst);           // bool(false)
var_dump(Carbon::createFromDate(2012, 9, 1)->dst);           // bool(false)
var_dump(Carbon::createFromDate(2012, 9, 1)->isDST());       // bool(false)

// Indicates if the instance is in the same timezone as the local timezone
var_dump(Carbon::now()->local);                              // bool(true)
var_dump(Carbon::now('America/Vancouver')->local);           // bool(false)
var_dump(Carbon::now()->isLocal());                          // bool(true)
var_dump(Carbon::now('America/Vancouver')->isLocal());       // bool(false)
var_dump(Carbon::now()->isUtc());                            // bool(true)
var_dump(Carbon::now('America/Vancouver')->isUtc());         // bool(false)
// can also be written ->isUTC()

// Indicates if the instance is in the UTC timezone
var_dump(Carbon::now()->utc);                                // bool(true)
// London is not UTC on summer time
var_dump(Carbon::parse('2018-10-01', 'Europe/London')->utc); // bool(false)
// London is UTC on winter time
var_dump(Carbon::parse('2018-11-01', 'Europe/London')->utc); // bool(true)
var_dump(Carbon::createFromTimestampUTC(0)->utc);            // bool(true)

// Gets the DateTimeZone instance
echo get_class(Carbon::now()->timezone);                     // Carbon\CarbonTimeZone
echo "\n";
echo get_class(Carbon::now()->tz);                           // Carbon\CarbonTimeZone
echo "\n";

// Gets the DateTimeZone instance name, shortcut for ->timezone->getName()
echo Carbon::now()->timezoneName;                            // UTC
echo "\n";
echo Carbon::now()->tzName;                                  // UTC
echo "\n";

// You can get any property dynamically too:
$unit = 'second';
var_dump(Carbon::now()->get($unit));                         // int(9)
// equivalent to:
var_dump(Carbon::now()->$unit);                              // int(9)
// If you have plural unit name, use singularUnit()
$unit = Carbon::singularUnit('seconds');
var_dump(Carbon::now()->get($unit));                         // int(9)
// Prefer using singularUnit() because some plurals are not the word with S:
var_dump(Carbon::pluralUnit('century'));                     // string(9) "centuries"
var_dump(Carbon::pluralUnit('millennium'));                  // string(9) "millennia"

通过属性值设置

$dt = Carbon::now();

$dt->year = 1975;
$dt->month = 13;             // would force year++ and month = 1
$dt->month = 5;
$dt->day = 21;
$dt->hour = 22;
$dt->minute = 32;
$dt->second = 5;

$dt->timestamp = 169957925;  // This will not change the timezone
// Same as:
$dt->setTimestamp(169957925);
$dt->timestamp(169957925);

// Set the timezone via DateTimeZone instance or string
$dt->tz = new DateTimeZone('Europe/London');
$dt->tz = 'Europe/London';

// The ->timezone is also available for backward compatibility but
// it will be overridden by native php DateTime class as soon as
// the object is dump (passed foreach, serialize, var_export, clone, etc.)
// making the Carbon setter inefficient, if it happen, you can cleanup
// those overridden properties by calling ->cleanupDumpProperties() on
// the instance, but we rather recommend to simply use ->tz instead
// of ->timezone everywhere.

// verbose way:
$dt->setYear(2001);
echo $dt->year;      // 2001
echo "\n";

// set/get method:
$dt->year(2002);
echo $dt->year();    // 0000-05-22 03:32:05
echo "\n";

// dynamic way:
$dt->set('year', 2003);
echo $dt->get('year'); // 2003
echo "\n";

// these methods exist for every units even for calculated properties such as:
echo $dt->dayOfYear(35)->format('Y-m-d'); // 2003-02-04

toArray 输出数组信息,toObject 对象信息

$date = CarbonImmutable::parse('2020-06-29 16:55:0');
$date->locale('zh')->format('Y-m-d H:i:s');    // 4:55 pm Monday 29th June 2020
dump($date->toArray());

黑白课堂
黑白课堂

比较日期

  • equalTo/eq 相等
  • notEqualTo/ne 不相等
  • greaterThan/gt 大于
  • greaterThanOrEqualTo/gte 大于或等于
  • lessThan/lt 小于
  • lessThanOrEqualTo/lte 小于或等于
echo Carbon::now()->tzName;                        // UTC
$first = Carbon::create(2012, 9, 5, 23, 26, 11);
$second = Carbon::create(2012, 9, 5, 20, 26, 11, 'America/Vancouver');

echo $first->toDateTimeString();                   // 2012-09-05 23:26:11
echo $first->tzName;                               // UTC
echo $second->toDateTimeString();                  // 2012-09-05 20:26:11
echo $second->tzName;                              // America/Vancouver

var_dump($first->equalTo($second));                // bool(false)
// equalTo is also available on CarbonInterval and CarbonPeriod
var_dump($first->notEqualTo($second));             // bool(true)
// notEqualTo is also available on CarbonInterval and CarbonPeriod
var_dump($first->greaterThan($second));            // bool(false)
// greaterThan is also available on CarbonInterval
var_dump($first->greaterThanOrEqualTo($second));   // bool(false)
// greaterThanOrEqualTo is also available on CarbonInterval
var_dump($first->lessThan($second));               // bool(true)
// lessThan is also available on CarbonInterval
var_dump($first->lessThanOrEqualTo($second));      // bool(true)
// lessThanOrEqualTo is also available on CarbonInterval

$first->setDateTime(2012, 1, 1, 0, 0, 0);
$second->setDateTime(2012, 1, 1, 0, 0, 0);         // Remember tz is 'America/Vancouver'

var_dump($first->equalTo($second));                // bool(false)
var_dump($first->notEqualTo($second));             // bool(true)
var_dump($first->greaterThan($second));            // bool(false)
var_dump($first->greaterThanOrEqualTo($second));   // bool(false)
var_dump($first->lessThan($second));               // bool(true)
var_dump($first->lessThanOrEqualTo($second));      // bool(true)

// All have short hand aliases and PHP equivalent code:

var_dump($first->eq($second));                     // bool(false)
var_dump($first->equalTo($second));                // bool(false)
var_dump($first == $second);                       // bool(false)

var_dump($first->ne($second));                     // bool(true)
var_dump($first->notEqualTo($second));             // bool(true)
var_dump($first != $second);                       // bool(true)

var_dump($first->gt($second));                     // bool(false)
var_dump($first->greaterThan($second));            // bool(false)
var_dump($first->isAfter($second));                // bool(false)
var_dump($first > $second);                        // bool(false)

var_dump($first->gte($second));                    // bool(false)
var_dump($first->greaterThanOrEqualTo($second));   // bool(false)
var_dump($first >= $second);                       // bool(false)

var_dump($first->lt($second));                     // bool(true)
var_dump($first->lessThan($second));               // bool(true)
var_dump($first->isBefore($second));               // bool(true)
var_dump($first < $second);                        // bool(true)

var_dump($first->lte($second));                    // bool(true)
var_dump($first->lessThanOrEqualTo($second));      // bool(true)
var_dump($first <= $second);                       // bool(true)

between/isBetween 在时间内

between 参数3,默认值是true,它确定其介于边界之间还是等于边界

$first = Carbon::create(2012, 9, 5, 1);
$second = Carbon::create(2012, 9, 5, 5);
var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second));          // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second));          // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second, false));   // bool(false)
var_dump(Carbon::create(2012, 9, 5, 5)->isBetween($first, $second, false)); // bool(false)

加减方法

$dt = Carbon::create(2012, 1, 31, 0);

echo $dt->toDateTimeString();            // 2012-01-31 00:00:00

echo $dt->addCenturies(5);               // 2512-01-31 00:00:00
echo $dt->addCentury();                  // 2612-01-31 00:00:00
echo $dt->subCentury();                  // 2512-01-31 00:00:00
echo $dt->subCenturies(5);               // 2012-01-31 00:00:00

echo $dt->addYears(5);                   // 2017-01-31 00:00:00
echo $dt->addYear();                     // 2018-01-31 00:00:00
echo $dt->subYear();                     // 2017-01-31 00:00:00
echo $dt->subYears(5);                   // 2012-01-31 00:00:00

echo $dt->addQuarters(2);                // 2012-07-31 00:00:00
echo $dt->addQuarter();                  // 2012-10-31 00:00:00
echo $dt->subQuarter();                  // 2012-07-31 00:00:00
echo $dt->subQuarters(2);                // 2012-01-31 00:00:00

echo $dt->addMonths(60);                 // 2017-01-31 00:00:00
echo $dt->addMonth();                    // 2017-03-03 00:00:00 equivalent of $dt->month($dt->month + 1); so it wraps
echo $dt->subMonth();                    // 2017-02-03 00:00:00
echo $dt->subMonths(60);                 // 2012-02-03 00:00:00

echo $dt->addDays(29);                   // 2012-03-03 00:00:00
echo $dt->addDay();                      // 2012-03-04 00:00:00
echo $dt->subDay();                      // 2012-03-03 00:00:00
echo $dt->subDays(29);                   // 2012-02-03 00:00:00

echo $dt->addWeekdays(4);                // 2012-02-09 00:00:00
echo $dt->addWeekday();                  // 2012-02-10 00:00:00
echo $dt->subWeekday();                  // 2012-02-09 00:00:00
echo $dt->subWeekdays(4);                // 2012-02-03 00:00:00

echo $dt->addWeeks(3);                   // 2012-02-24 00:00:00
echo $dt->addWeek();                     // 2012-03-02 00:00:00
echo $dt->subWeek();                     // 2012-02-24 00:00:00
echo $dt->subWeeks(3);                   // 2012-02-03 00:00:00

echo $dt->addHours(24);                  // 2012-02-04 00:00:00
echo $dt->addHour();                     // 2012-02-04 01:00:00
echo $dt->subHour();                     // 2012-02-04 00:00:00
echo $dt->subHours(24);                  // 2012-02-03 00:00:00

echo $dt->addMinutes(61);                // 2012-02-03 01:01:00
echo $dt->addMinute();                   // 2012-02-03 01:02:00
echo $dt->subMinute();                   // 2012-02-03 01:01:00
echo $dt->subMinutes(61);                // 2012-02-03 00:00:00

echo $dt->addSeconds(61);                // 2012-02-03 00:01:01
echo $dt->addSecond();                   // 2012-02-03 00:01:02
echo $dt->subSecond();                   // 2012-02-03 00:01:01
echo $dt->subSeconds(61);                // 2012-02-03 00:00:00

echo $dt->addMilliseconds(61);           // 2012-02-03 00:00:00
echo $dt->addMillisecond();              // 2012-02-03 00:00:00
echo $dt->subMillisecond();              // 2012-02-03 00:00:00
echo $dt->subMillisecond(61);            // 2012-02-03 00:00:00

echo $dt->addMicroseconds(61);           // 2012-02-03 00:00:00
echo $dt->addMicrosecond();              // 2012-02-03 00:00:00
echo $dt->subMicrosecond();              // 2012-02-03 00:00:00
echo $dt->subMicroseconds(61);           // 2012-02-03 00:00:00

// and so on for any unit: millenium, century, decade, year, quarter, month, week, day, weekday,
// hour, minute, second, microsecond.

// Generic methods add/sub (or subtract alias) can take many different arguments:
echo $dt->add(61, 'seconds');                      // 2012-02-03 00:01:01
echo $dt->sub('1 day');                            // 2012-02-02 00:01:01
echo $dt->add(CarbonInterval::months(2));          // 2012-04-02 00:01:01
echo $dt->subtract(new DateInterval('PT1H'));      // 2012-04-01 23:01:01

增减可能会溢出的可能性

默认情况下,Carbon依赖于基础父类PHP DateTime行为。结果,增加或减少月份可能会溢出

$dt = CarbonImmutable::create(2017, 1, 31, 0);

echo $dt->addMonth();                    // 2017-03-03 00:00:00
echo "\n";
echo $dt->subMonths(2);                  // 2016-12-01 00:00:00

解决

$dt = CarbonImmutable::create(2017, 1, 31, 0);
$dt->settings([
    'monthOverflow' => false,
]);

echo $dt->addMonth();                    // 2017-02-28 00:00:00
echo "\n";
echo $dt->subMonths(2);                  // 2016-11-30 00:00:00

或者使用方法

 echo $dt->addMonthNoOverflow();   
 echo $dt->subMonthsNoOverflow(2);

copy 时间和时区值都将复制到新实例

$dt = Carbon::now();
echo $dt->diffInYears($dt->copy()->addYear());  // 1

取最小和最大日期 min/minimum,max/maximum

$dt1 = Carbon::createMidnightDate(2012, 1, 1);
$dt2 = Carbon::createMidnightDate(2014, 1, 30);
echo $dt1->min($dt2);                              // 2012-01-01 00:00:00
echo $dt1->minimum($dt2);                          // 2012-01-01 00:00:00
// Also works with string
echo $dt1->minimum('2014-01-30');                  // 2012-01-01 00:00:00

$dt1 = Carbon::createMidnightDate(2012, 1, 1);
$dt2 = Carbon::createMidnightDate(2014, 1, 30);
echo $dt1->max($dt2);                              // 2014-01-30 00:00:00
echo $dt1->maximum($dt2);                          // 2014-01-30 00:00:00

判断日期值是否等于值

$dt = Carbon::now();
$dt2 = Carbon::createFromDate(1987, 4, 23);

$dt->isSameAs('w', $dt2); // w is the date of the week, so this will return true if $dt and $dt2
                          // the same day of week (both monday or both sunday, etc.)
                          // you can use any format and combine as much as you want.
$dt->isFuture();
$dt->isPast();

$dt->isSameYear($dt2);
$dt->isCurrentYear();
$dt->isNextYear();
$dt->isLastYear();
$dt->isLongYear(); // see https://en.wikipedia.org/wiki/ISO_8601#Week_dates
$dt->isLeapYear();

$dt->isSameQuarter($dt2); // same quarter of the same year of the given date
$dt->isSameQuarter($dt2, false); // same quarter (3 months) no matter the year of the given date
$dt->isCurrentQuarter();
$dt->isNextQuarter(); // date is in the next quarter
$dt->isLastQuarter(); // in previous quarter

$dt->isSameMonth($dt2); // same month of the same year of the given date
$dt->isSameMonth($dt2, false); // same month no matter the year of the given date
$dt->isCurrentMonth();
$dt->isNextMonth();
$dt->isLastMonth();

$dt->isWeekday();
$dt->isWeekend();
$dt->isMonday();
$dt->isTuesday();
$dt->isWednesday();
$dt->isThursday();
$dt->isFriday();
$dt->isSaturday();
$dt->isSunday();
$dt->isDayOfWeek(Carbon::SATURDAY); // is a saturday
$dt->isLastOfMonth(); // is the last day of the month

$dt->is('Sunday');
$dt->is('June');
$dt->is('2019');
$dt->is('12:23');
$dt->is('2 June 2019');
$dt->is('06-02');

$dt->isSameDay($dt2); // Same day of same month of same year
$dt->isCurrentDay();
$dt->isYesterday();
$dt->isToday();
$dt->isTomorrow();
$dt->isNextWeek();
$dt->isLastWeek();

$dt->isSameHour($dt2);
$dt->isCurrentHour();
$dt->isSameMinute($dt2);
$dt->isCurrentMinute();
$dt->isSameSecond($dt2);
$dt->isCurrentSecond();

$dt->isStartOfDay(); // check if hour is 00:00:00
$dt->isMidnight(); // check if hour is 00:00:00 (isStartOfDay alias)
$dt->isEndOfDay(); // check if hour is 23:59:59
$dt->isMidday(); // check if hour is 12:00:00 (or other midday hour set with Carbon::setMidDayAt())
$born = Carbon::createFromDate(1987, 4, 23);
$noCake = Carbon::createFromDate(2014, 9, 26);
$yesCake = Carbon::createFromDate(2014, 4, 23);
$overTheHill = Carbon::now()->subYears(50);
var_dump($born->isBirthday($noCake));              // bool(false)
var_dump($born->isBirthday($yesCake));             // bool(true)
var_dump($overTheHill->isBirthday());              // bool(true) -> default compare it to today!

// isCurrentX, isSameX, isNextX and isLastX are available for each unit

四舍五入单位输出

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->roundMillisecond()->format('H:i:s.u');   // 15:32:45.654000

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->roundSecond()->format('H:i:s.u');        // 15:32:46.000000

$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->floorSecond()->format('H:i:s.u');        // 15:32:45.000000

$dt = new Carbon('2012-01-31 15:32:15');
echo $dt->roundMinute()->format('H:i:s');          // 15:32:00

$dt = new Carbon('2012-01-31 15:32:15');
echo $dt->ceilMinute()->format('H:i:s');           // 15:33:00

// and so on up to millennia!

// precision rounding can be set, example: rounding to ten minutes
$dt = new Carbon('2012-01-31 15:32:15');
echo $dt->roundMinute(10)->format('H:i:s');        // 15:30:00

// and round, floor and ceil methods are shortcut for second rounding:
$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->round()->format('H:i:s.u');              // 15:32:46.000000
$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->floor()->format('H:i:s.u');              // 15:32:45.000000
$dt = new Carbon('2012-01-31 15:32:45.654321');
echo $dt->ceil()->format('H:i:s.u');               // 15:32:46.000000

// you can also pass the unit dynamically (and still precision as second argument):
$dt = new Carbon('2012-01-31');
echo $dt->roundUnit('month', 2)->format('Y-m-d');  // 2012-03-01
$dt = new Carbon('2012-01-31');
echo $dt->floorUnit('month')->format('Y-m-d');     // 2012-03-01
$dt = new Carbon('2012-01-31');
echo $dt->ceilUnit('month', 4)->format('Y-m-d');   // 2012-05-01

常量

var_dump(Carbon::SUNDAY);                          // int(0)
var_dump(Carbon::MONDAY);                          // int(1)
var_dump(Carbon::TUESDAY);                         // int(2)
var_dump(Carbon::WEDNESDAY);                       // int(3)
var_dump(Carbon::THURSDAY);                        // int(4)
var_dump(Carbon::FRIDAY);                          // int(5)
var_dump(Carbon::SATURDAY);                        // int(6)

var_dump(Carbon::YEARS_PER_CENTURY);               // int(100)
var_dump(Carbon::YEARS_PER_DECADE);                // int(10)
var_dump(Carbon::MONTHS_PER_YEAR);                 // int(12)
var_dump(Carbon::WEEKS_PER_YEAR);                  // int(52)
var_dump(Carbon::DAYS_PER_WEEK);                   // int(7)
var_dump(Carbon::HOURS_PER_DAY);                   // int(24)
var_dump(Carbon::MINUTES_PER_HOUR);                // int(60)
var_dump(Carbon::SECONDS_PER_MINUTE);              // int(60)

序列化

dt = Carbon::create(2012, 12, 25, 20, 30, 00, 'Europe/Moscow');

echo serialize($dt);                                              // O:13:"Carbon\Carbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}
// same as:
echo $dt->serialize();                                            // O:13:"Carbon\Carbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}

$dt = 'O:13:"Carbon\Carbon":3:{s:4:"date";s:26:"2012-12-25 20:30:00.000000";s:13:"timezone_type";i:3;s:8:"timezone";s:13:"Europe/Moscow";}';

echo unserialize($dt)->format('Y-m-d\TH:i:s.uP T');               // 2012-12-25T20:30:00.000000+04:00 MSK
// same as:
echo Carbon::fromSerialized($dt)->format('Y-m-d\TH:i:s.uP T');    // 2012-12-25T20:30:00.000000+04:00 MSK

周数

一周的第一天是周日,一年的第一周是包含1月1日的周

$en = CarbonImmutable::now()->locale('en_US');
$ar = CarbonImmutable::now()->locale('ar');

var_dump($en->firstWeekDay);                           // int(0)
var_dump($en->lastWeekDay);                            // int(6)
var_dump($en->startOfWeek()->format('Y-m-d H:i'));     // string(16) "2020-07-26 00:00"
var_dump($en->endOfWeek()->format('Y-m-d H:i'));       // string(16) "2020-08-01 23:59"

echo "-----------\n";

// We still can force to use an other day as start/end of week
$start = $en->startOfWeek(Carbon::TUESDAY);
$end = $en->endOfWeek(Carbon::MONDAY);
var_dump($start->format('Y-m-d H:i'));                 // string(16) "2020-07-28 00:00"
var_dump($end->format('Y-m-d H:i'));                   // string(16) "2020-08-03 23:59"

echo "-----------\n";

var_dump($ar->firstWeekDay);                           // int(6)
var_dump($ar->lastWeekDay);                            // int(5)
var_dump($ar->startOfWeek()->format('Y-m-d H:i'));     // string(16) "2020-07-25 00:00"
var_dump($ar->endOfWeek()->format('Y-m-d H:i'));       // string(16) "2020-07-31 23:59"

$en = CarbonImmutable::parse('2015-02-05'); // use en_US as default locale

echo "-----------\n";

var_dump($en->weeksInYear());                          // int(52)
var_dump($en->isoWeeksInYear());                       // int(53)

$en = CarbonImmutable::parse('2017-02-05');

echo "-----------\n";

var_dump($en->week());                                 // int(6)
var_dump($en->isoWeek());                              // int(5)
var_dump($en->week(1)->format('Y-m-d H:i'));           // string(16) "2017-01-01 00:00"
var_dump($en->isoWeek(1)->format('Y-m-d H:i'));        // string(16) "2017-01-08 00:00"
var_dump($en->weekday());                              // int(0)
var_dump($en->isoWeekday());                           // int(7)
var_dump($en->weekday(3)->format('Y-m-d H:i'));        // string(16) "2017-02-08 00:00"
var_dump($en->isoWeekday(3)->format('Y-m-d H:i'));     // string(16) "2017-02-01 00:00"

$en = CarbonImmutable::parse('2017-01-01');

echo "-----------\n";

var_dump($en->weekYear());                             // int(2017)
var_dump($en->isoWeekYear());                          // int(2016)
var_dump($en->weekYear(2016)->format('Y-m-d H:i'));    // string(16) "2015-12-27 00:00"
var_dump($en->isoWeekYear(2016)->format('Y-m-d H:i')); // string(16) "2017-01-01 00:00"
var_dump($en->weekYear(2015)->format('Y-m-d H:i'));    // string(16) "2014-12-28 00:00"
var_dump($en->isoWeekYear(2015)->format('Y-m-d H:i')); // string(16) "2015-12-27 00:00"

// Note you still can force first day of week and year to use:
$en = CarbonImmutable::parse('2017-01-01');

echo "-----------\n";

var_dump($en->weeksInYear(null, 6, 12));               // int(52)
var_dump($en->isoWeeksInYear(null, 6, 12));            // int(52)
var_dump($en->week(null, 6, 12));                      // int(52)
var_dump($en->isoWeek(null, 6, 12));                   // int(52)
var_dump($en->weekYear(null, 6, 12));                  // int(2016)
var_dump($en->isoWeekYear(null, 6, 12));               // int(2016)
var_dump($en->weekYear(2016, 6, 12)->format('Y-m-d H:i')); // string(16) "2017-01-01 00:00"
var_dump($en->isoWeekYear(2016, 6, 12)->format('Y-m-d H:i')); // string(16) "2017-01-01 00:00"
// Then you can see using a method or its ISO variant return identical results