使用Carbon,在Laravel和PHP中更轻松的日期/时间

The Scotchmas Day 6 giveaway can be found at the end of this article.

在本文的末尾可以找到Scotchmas Day 6赠品。

Working with date and time in PHP is not the easiest or most clear of tasks. We have to deal with strtotime, formatting issues, lots of calculations, and more.

在PHP中使用日期和时间并不是最简单或最不容易完成的任务。 我们必须处理strtotime ,格式问题,大量计算等等。

The nifty package called Carbon can help make dealing with date/time in PHP much easier and more semantic so that our code can become more readable and maintainable.

名为Carbon的漂亮软件包可以帮助使PHP中的日期/时间处理变得更加轻松和语义化,从而使我们的代码更具可读性和可维护性。

(Carbon)

Carbon is a package by Brian Nesbit that extends PHP's own DateTime class.

Carbon是Brian Nesbit的软件包,它扩展了PHP自己的DateTime类。

ql5GP2I

It provides some nice functionality to deal with dates in PHP. Specifically things like:

它提供了一些不错的功能来处理PHP中的日期。 具体来说是这样的:

  • Dealing with timezones

    处理时区
  • Getting current time easily

    轻松获取当前时间
  • Converting a datetime into something readable

    将日期时间转换为可读的内容
  • Parse an English phrase into datetime (first day of January 2016)

    将英语短语解析为日期时间( 2016年1月的第一天
  • Add and Subtract dates (+ 2 weeks, -6 months)

    加减日期( + 2周-6个月
  • Semantic way of dealing with dates

    处理日期的语义方式

All of the above lead to a very useful package that makes it a breeze to deal with times in PHP.

上面所有这些导致了一个非常有用的软件包,这使得处理PHP中的时间变得轻而易举。

建立 (Setup)

In order to use Carbon, you'll need to import Carbon from the Carbon namespace. Luckily for us, Carbon is already included in Laravel so there's no need to go and add it with Composer.

为了使用Carbon,您需要从Carbon名称空间导入Carbon。 对我们来说幸运的是,Carbon已包含在Laravel中,因此无需去与Composer添加它。

Whenever we need to use Carbon, we can import it like so:

每当我们需要使用Carbon时,我们都可以这样导入它:

<?php
use Carbon\Carbon;

After importing, let's look at some cool things we can do with this great package.

导入后,让我们看一下使用此出色包可以做的一些很棒的事情。

获取特定的日期/时间 (Getting a Specific Date/Time)

// get the current time  - 2015-12-19 10:10:54
$current = Carbon::now();
$current = new Carbon();

// get today - 2015-12-19 00:00:00
$today = Carbon::today();

// get yesterday - 2015-12-18 00:00:00
$yesterday = Carbon::yesterday();

// get tomorrow - 2015-12-20 00:00:00
$tomorrow = Carbon::tomorrow();

// parse a specific string - 2016-01-01 00:00:00
$newYear = new Carbon('first day of January 2016');

// set a specific timezone - 2016-01-01 00:00:00
$newYearPST = new Carbon('first day of January 2016', 'America\Pacific');

使用更精细的控制来创建日期 (Creating Dates with More Fine Grained Control)

In addition to the quick ways to define date/times, Carbon also let's us create date/times from a specific number of arguments.

除了快速定义日期/时间的方法外,Carbon还让我们根据特定数量的参数创建日期/时间。

Carbon::createFromDate($year, $month, $day, $tz);
Carbon::createFromTime($hour, $minute, $second, $tz);
Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

These are very helpful when you get some sort of date or time in a format that isn't normally recognized by Carbon. If you pass in null for any of those attributes, it will default to current.

当您获得某些通常不属于Carbon的格式的日期或时间时,这些功能非常有用。 如果您为这些属性中的任何一个传递null ,它将默认为current。

操作日期/时间 (Manipulating the Date/Time)

Grabbing the date/time isn't the only thing you'll need to do when working with dates. You'll often need to manipulate the date or time.

掌握日期/时间并不是处理日期时唯一要做的事情。 您通常需要操纵日期或时间。

For instance, when creating a trial period for a user, you will want the trial period to expire after a certain amount of time. So let's say we have a 30 day trial period. We could easily calculate that time with add and subtract.

例如,当为用户创建试用期时,您将希望试用期在一定时间后过期。 假设我们有30天的试用期。 我们可以轻松地通过addsubtract计算该时间。

For this trial period, we would do:

在此试用期内,我们将:

// get the current time
$current = Carbon::now();

// add 30 days to the current time
$trialExpires = $current->addDays(30);

From the Carbon docs, here are some of the other add() and sub() methods available to us:

Carbon文档中 ,这是我们可以使用的其他一些add()sub()方法:

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

echo $dt->toDateTimeString();            // 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->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

吸气剂和二传手 (Getters and Setters)

Another quick way to manipulate or read the time is to use the getters and setters available.

操纵或读取时间的另一种快速方法是使用可用的getter和setter。

$dt = Carbon::now();

// set some things
$dt->year   = 2015;
$dt->month  = 04;
$dt->day    = 21;
$dt->hour   = 22;
$dt->minute = 32;
$dt->second = 5;

// get some things
var_dump($dt->year);
var_dump($dt->month);
var_dump($dt->day);
var_dump($dt->hour);
var_dump($dt->second);
var_dump($dt->dayOfWeek);
var_dump($dt->dayOfYear);
var_dump($dt->weekOfMonth);
var_dump($dt->daysInMonth);

We can even string together some setters

我们甚至可以将一些二传手串在一起

$dt = Carbon::now();

$dt->year(1975)->month(5)->day(21)->hour(22)->minute(32)->second(5)->toDateTimeString();
$dt->setDate(1975, 5, 21)->setTime(22, 32, 5)->toDateTimeString();
$dt->setDateTime(1975, 5, 21, 22, 32, 5)->toDateTimeString();

格式化 (Formatting)

In that example above, you may have noticed the -&gt;toDateTimeString() method. We can easily format the date/time for our purposes. In that case, we got a datetime string.

在上面的示例中,您可能已经注意到-&gt;toDateTimeString()方法。 我们可以根据自己的目的轻松格式化日期/时间。 在这种情况下,我们得到了一个日期时间字符串。

$dt = Carbon::now();

echo $dt->toDateString();               // 2015-12-19
echo $dt->toFormattedDateString();      // Dec 19, 2015
echo $dt->toTimeString();               // 10:10:16
echo $dt->toDateTimeString();           // 2015-12-19 10:10:16
echo $dt->toDayDateTimeString();        // Sat, Dec 19, 2015 10:10 AM

// ... of course format() is still available
echo $dt->format('l jS \\of F Y h:i:s A');         // Saturday 19th of December 2015 10:10:16 AM

相对时间 (Relative Time)

Carbon let's us easily display time relatively with the diff() methods.

Carbon让我们使用diff()方法轻松地相对显示时间。

For instance, let's say we have a blog and wanted to show a published time of 3 hours ago. We would be able to do that with these methods.

例如,假设我们有一个博客,想要显示3小时前的发布时间。 使用这些方法,我们将能够做到这一点。

寻找差异 (Finding the Difference)

These methods are used to just find the number of difference.

这些方法仅用于查找差异数。

$current = Carbon::now();
$dt      = Carbon::now();

$dt = $dt->subHours(6);
echo $dt->diffInHours($current);         // -6
echo $current->diffInHours($dt);         // 6

$future = $current->addMonth();
$past   = $current->subMonths(2);
echo $current->diffInDays($future);      // 31
echo $current->diffInDays($past);        // -62

向人类展示差异 (Displaying the Difference for Humans)

Displaying time relatively has become popular in the past few years. This can be seen across the social networks like Twitter and Facebook.

在过去几年中,相对地显示时间变得很流行。 可以在Twitter和Facebook等社交网络上看到这一点。

For example, instead of displaying the time of a post like 8:12am, the time will be displayed as 3 hrs.

例如,该时间不会显示为8:12 am之类的时间,而是显示为3 hrs

These methods are used for calculating the difference and also converting it to a humanly readable format.

这些方法用于计算差异并将其转换为人类可读的格式。

There are four different possibilities for how to display times like this:

像这样显示时间有四种不同的可能性:

  • When comparing a value in the past to default now:
    • 1 hour ago
    • 5 months ago

    将过去的值与现在的默认值进行比较时:
    • 1小时前
    • 5个月前
  • When comparing a value in the future to default now:
    • 1 hour from now
    • 5 months from now

    将将来的值与现在的默认值进行比较时:
    • 从现在起1小时
    • 从现在起5个月
  • When comparing a value in the past to another value:
    • 1 hour before
    • 5 months before

    将过去的值与另一个值进行比较时:
    • 1小时前
    • 5个月前
  • When comparing a value in the future to another value:
    • 1 hour after
    • 5 months after

    将将来的值与另一个值进行比较时:
    • 1小时后
    • 5个月后
$dt     = Carbon::now();
$past   = $dt->subMonth();
$future = $dt->addMonth();

echo $dt->subDays(10)->diffForHumans();     // 10 days ago
echo $dt->diffForHumans($past);             // 1 month ago
echo $dt->diffForHumans($future);           // 1 month before

结论 (Conclusion)

There's plenty more that Carbon can do. Be sure to look through the official Carbon docs. Hopefully this helps use date/times easier in PHP and speeds up development times!

Carbon可以做更多的事情。 请务必仔细阅读Carbon官方文档 。 希望这有助于在PHP中更轻松地使用日期/时间并加快开发时间!

苏格兰第六天赠品 (Scotchmas Day 6 Giveaway)

a Rafflecopter giveaway

Rafflecopter赠品

翻译自: https://scotch.io/tutorials/easier-datetime-in-laravel-and-php-with-carbon

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值