carbon() 函数可用于使用 Twig 处理日期和时间,搭配一个 Carbon 对象 及其所有可用函数。
所提供的值将根据 cms.timezone 配置设置自动转换为当前时区,该设置可以使用站点定义进行设置。
要输出当前的日期时间值:
{{ carbon('now') }}要指定自定义值:
{{ carbon('2024-01-01 02:13:23') }}
format 方法可用于应用各种格式。
Meeting starts at {{ carbon(event.start_at).format('H:i') }} in Johannesburg.根据区域设置,使用 ISO 标准格式化日期或时间。这取代了已弃用的 formatLocalized 方法。
{{ carbon(article.created_at).isoFormat('DD.MM.YYYY HH:mm:ss') }}例如,要用法语显示月份和年份:
{{ carbon(someDate).isoFormat('MMMM Y') }} {# outputs "octobre 2025" #}diffForHumans 方法将以人类可读的文本形式,渲染日期与当前时间之间的差值。
{{ carbon(post.published_at).diffForHumans() }}你可以使用该格式来生成缓存清除 URL。
// Outputs: 10.26.22.22.53.31
carbon('now').format('m.d.y.H.i.s')然后构建 URL,如下所示。
<img src="{{ 'assets/images/image_file.jpg'|theme }}?{{ carbon('now').format('m.d.y.H.i.s') }}" alt="" />以下值在格式化日期和时间时可用。您可以将这些代码与 format 方法一起使用。
| Day Format | Example |
|---|---|
d | 01 through 31 |
D | Mon through Sun |
j | 1 through 31 |
l | Sunday through Saturday |
N | 1 (Monday) to 7 (Sunday) |
S | st, nd, rd, th |
w | 0 (Sunday) through 6 (Saturday) |
z | 0 through 365 |
| Week Format | Example |
|---|---|
W | 42 (42nd week in year) |
| Month Format | Example |
|---|---|
F | January through December |
m | 01 through 12 |
M | Jan through Dec |
n | 1 through 12 |
t | 28 through 31 |
| Year Format | Example |
|---|---|
Y | 1985, 1991, 2012, 2014, ... |
y | 85, 91, 12, 14, ... |
o | Same as Y, except based on week ending |
L | 1 (leap year), 0 otherwise |
| Time Format | Example |
|---|---|
a | am or pm |
A | AM or PM |
B | 000 through 999 |
g | 1 through 12 |
G | 0 through 23 |
h | 01 through 12 |
H | 01 through 23 |
i | 00 through 59 |
u | 123456 (microseconds) |
| Timezone Format | Example |
|---|---|
e | UTC, GMT, Atlantic/Azores |
I | 1 (daylight), 0 otherwise |
O | +0200 |
P | +02:00 |
T | EST, MDT, ... |
Z | -43200 through 50400 (timezone offset) |
| Date & Time Format | Example |
|---|---|
c | 2004-02-12T15:19:21+00:00 |
r | Thu, 21 Dec 2000 16:01:07 +0200 |
U | Seconds since Jan 1 1970 00:00:00 GMT |