PHP 时间类 Carbon 中文手册

包说明

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
Code Example Description
OD 5 Day number with alternative numbers such as 三 for 3 if locale is ja_JP
OM 1 Month number with alternative numbers such as ၀၂ for 2 if locale is my_MM
OY 2017 Year number with alternative numbers such as ۱۹۹۸ for 1998 if locale is fa
OH 17 24-hours number with alternative numbers such as ႑႓ for 13 if locale is shn_MM
Oh 5 12-hours number with alternative numbers such as 十一 for 11 if locale is lzh_TW
Om 4 Minute number with alternative numbers such as ୫୭ for 57 if locale is or
Os 5 Second number with alternative numbers such as 十五 for 15 if locale is ja_JP
D 5 Day of month number (from 1 to 31)
DD 05 Day of month number with trailing zero (from 01 to 31)
Do 5th Day of month with ordinal suffix (from 1st to 31th), translatable
d 4 Day of week number (from 0 (Sunday) to 6 (Saturday))
dd Th Minified day name (from Su to Sa), transatable
ddd Thu Short day name (from Sun to Sat), transatable
dddd Thursday Day name (from Sunday to Saturday), transatable
DDD 5 Day of year number (from 1 to 366)
DDDD 005 Day of year number with trailing zeros (3 digits, from 001 to 366)
DDDo 5th Day of year number with ordinal suffix (from 1st to 366th), translatable
e 4 Day 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)
E 4 Day of week number (from 1 (Monday) to 7 (Sunday))
H 17 Hour from 0 to 23
HH 17 Hour with trailing zero from 00 to 23
h 5 Hour from 0 to 12
hh 05 Hour with trailing zero from 00 to 12
k 17 Hour from 1 to 24
kk 17 Hour with trailing zero from 01 to 24
m 4 Minute from 0 to 59
mm 04 Minute with trailing zero from 00 to 59
a pm Meridiem am/pm
A PM Meridiem AM/PM
s 5 Second from 0 to 59
ss 05 Second with trailing zero from 00 to 59
S 0 Second tenth
SS 08 Second hundredth (on 2 digits with trailing zero)
SSS 084 Millisecond (on 3 digits with trailing zeros)
SSSS 0845 Second ten thousandth (on 4 digits with trailing zeros)
SSSSS 08451 Second hundred thousandth (on 5 digits with trailing zeros)
SSSSSS 084512 Microsecond (on 6 digits with trailing zeros)
SSSSSSS 0845120 Second ten millionth (on 7 digits with trailing zeros)
SSSSSSSS 08451200 Second hundred millionth (on 8 digits with trailing zeros)
SSSSSSSSS 084512000 Nanosecond (on 9 digits with trailing zeros)
M 1 Month from 1 to 12
MM 01 Month with trailing zero from 01 to 12
MMM Jan Short month name, translatable
MMMM January Month name, translatable
Mo 1st Month with ordinal suffix from 1st to 12th, translatable
Q 1 Quarter from 1 to 4
Qo 1st Quarter with ordinal suffix from 1st to 4th, translatable
G 2017 ISO week year (see ISO week date)
GG 2017 ISO week year (on 2 digits with trailing zero)
GGG 2017 ISO week year (on 3 digits with trailing zeros)
GGGG 2017 ISO week year (on 4 digits with trailing zeros)
GGGGG 02017 ISO week year (on 5 digits with trailing zeros)
g 2017 Week year according to locale settings, translatable
gg 2017 Week year according to locale settings (on 2 digits with trailing zero), translatable
ggg 2017 Week year according to locale settings (on 3 digits with trailing zeros), translatable
gggg 2017 Week year according to locale settings (on 4 digits with trailing zeros), translatable
ggggg 02017 Week year according to locale settings (on 5 digits with trailing zeros), translatable
W 1 ISO week number in the year (see ISO week date)
WW 01 ISO week number in the year (on 2 digits with trailing zero)
Wo 1st ISO week number in the year with ordinal suffix, translatable
w 1 Week number in the year according to locale settings, translatable
ww 01 Week number in the year according to locale settings (on 2 digits with trailing zero)
wo 1st Week number in the year according to locale settings with ordinal suffix, translatable
x 1483635845085 Millisecond-precision timestamp (same as date.getTime() in JavaScript)
X 1483635845 Timestamp (number of seconds since 1970-01-01)
Y 2017 Full year from -9999 to 9999
YY 17 Year on 2 digits from 00 to 99
YYYY 2017 Year on 4 digits from 0000 to 9999
YYYYY 02017 Year on 5 digits from 00000 to 09999
YYYYYY +002017 Year on 5 digits with sign from -09999 to +09999
z UTC Abbreviated time zone name
zz UTC Time zone name
Z +00:00 Time zone offset HH:mm
ZZ +0000 Time 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() 格式化

https://www.php.net/manual/en/datetime.format.php

 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());

黑白课堂
黑白课堂

需要花费 10个元宝,后才能查看完整内容 立即购买

提示

评论区 (0)

没有记录
支持 markdown,图片截图粘贴拖拽都可以自动上传。
黑白课堂

黑白课堂

混元大罗金仙 站长创业者玉树凌风每天醒来0收入

查看更多

最新视频课程

Laravel 的 PhpSpreadsheet 包入门

wap2App 入门讲解,100%速成,全面为你讲解。

ace.js 打造一款属于你的 Web 编辑器,入门文档。

Laravel Permission 中文文档

解释 OAuth 2.0 认证 和使用场景说明

Laravel 之 horizon 队列管理界面系统

钻级赞助商