Location>code7788 >text

PHP to Go Series | Carbon time manipulation tool posture

Popularity:775 ℃/2024-08-01 09:12:55

Hi everyone, I'm Codemaster Pioneer.

In the course of daily development, you will often encounter the processing of time, such as formatting timestamps, getting the time of yesterday or last week or last month, adding or subtracting based on the current time, etc. In PHP, there is a native function for processing time, strtotime, which we all know can only be used for basic purposes. In PHP there is a native function strtotime for time processing, we all know that this function can only meet the basic use, if you encounter more complex scenarios, it will be more cumbersome to deal with. PHP as the world's best language, in the face of this problem will naturally be a big brother out of the wheels, which appeared in the nesbot/carbon extension package. In fact, there is a third-party library, carbon, that does the same thing in Go. After reading the documentation, I was surprised to see that it looks exactly like PHP's extensions, and it looks like the Go guy is also a convert from PHP. This is a good thing because it reduces the cost of learning and makes it easier for us to get started.

Install the carbon package in the php_carbon directory using the composer command.

[manongsen@root ~]$ pwd
/home/manongsen/workspace/php_to_go/php_carbon
[manongsen@root php_carbon]$ composer require nesbot/carbon

In the go_carbon directory, use thego mod init Initialize the Go project and use thego get Install the carbon library.

[manongsen@root ~]$ pwd
/home/manongsen/workspace/php_to_go/go_carbon
[manongsen@root go_carbon]$ go mod init go_carbon
[manongsen@root go_carbon]$ go get /golang-module/carbon/v2

This is the structure of the project after initialization is complete.

[manongsen@root php_to_go]$ tree -L 2
.
├── 
├── go_carbon
│   ├── 
│   ├── 
│   └── 
└── php_carbon
    ├── 
    ├── 
    ├── 
    └── vendor

We set the timezone in the first line of the PHP script by using the date_default_timezone_set function, and then use require to load the dependencies. As you can see from the example code below, the Carbon tool is quite easy to use, as you can add and subtract days using the subDays and addDays functions, and use the diffForHumans function to output in a human-readable way. In addition, there are a number of examples not shown in the use, such as obtaining the current season, get the beginning and end of the week, the calculation of the time difference, to determine the current month, get the current is the first day of the week and so on, from the official documentation provided by the Carbon tool is still quite rich in terms of usage, almost can meet the business scenarios of the use of any.

<?php
date_default_timezone_set("Asia/Shanghai").

require 'vendor/';?

require 'vendor/'; use Carbon\Carbon.

// Get the current time
$now = Carbon::now(); print_r("Current time " .
print_r("Current time " . $now->toDateTimeString() . "\n");

// Get today's time
$today = Carbon::today();
print_r("Today's time " . $today->toDateString() . "\n");

// Get yesterday's time
$yesterday = Carbon::yesterday();
print_r("Time yesterday " . $yesterday->toDateString() . "\n");

// Get tomorrow's time
$tomorrow = Carbon::tomorrow();
print_r("Time tomorrow " . $tomorrow->toDateString() . "\n");

// 3 days ago
$threeDaysAgo = Carbon::today()->subDays(3);
print_r("3 days ago time " . $threeDaysAgo->toDateString(). "\n");

// 7 days ago
$sevenDaysAgo = Carbon::today()->subDays(7);
print_r("7 days ago time " . $sevenDaysAgo->toDateString(). "\n");

// human-readable time output
Carbon::setLocale('zh');

// 1 hour ago
$anHourAgo = Carbon::now()->subHours(1)->diffForHumans();
print_r($anHourAgo."\n");

// 1 day ago
$oneDayAgo = Carbon::now()->subDays(1)->diffForHumans();
print_r($oneDayAgo."\n");

// 1 month ago
$oneMonthAgo = Carbon::now()->subMonth()->diffForHumans();
print_r($oneMonthAgo."\n");

fulfillmentphp command can output the results of the above sample code.

[manongsen@root php_carbon]$ php
Current time 2024-06-27 22:23:11
Today's time 2024-06-27
Yesterday's time 2024-06-26
Time tomorrow 2024-06-28
Time 3 days ago 2024-06-24
7 days ago 2024-06-20
1 hour ago
1 day ago
1 month ago

Also in Go, it works like PHP, but packages are imported using the import keyword. If you're familiar with PHP's Carbon tool, it's easy to understand how to use it in Go, so it's a no-brainer.

package main

import (
"fmt"

"/golang-module/carbon/v2"
)

func main() {
// The current time
now := ().String()
("Current time %v\n", now)

// Get today's time
today := ().ToDateString()
("Today's time %v\n", today)

// Get yesterday's time
yesterday := ().ToDateString()
("Time yesterday %v\n", yesterday)

// Get tomorrow's time
tomorrow := ().ToDateString()
("Time tomorrow %v\n", tomorrow)

// 3 days ago
threeDaysAgo := ().SubDays(3).ToDateString()
("Time 3 days ago %v\n", threeDaysAgo)

// 7 days ago
sevenDaysAgo := ().SubDays(7).ToDateString()
("Time 7 days ago %v\n", sevenDaysAgo)

// Human-friendly readable format time format
lang := ()
("zh-CN")
c := (lang)
c := (lang) if ! = nil {
// Error handling
("err: %v\n", )
return
}

// 1 hour ago
anHourAgo := ().SubHours(1).DiffForHumans()
("%v\n", anHourAgo)

// 1 day ago
oneDayAgo := ().SubDays(1).DiffForHumans()
("%v\n", oneDayAgo)

// 1 month ago
oneMonthAgo := ().SubMonths(1).DiffForHumans()
("%v\n", oneMonthAgo)
}

fulfillmentgo run command will output the results of the above example code. The output is the same as the PHP output and there is no difference.

[manongsen@root go_carbon]$ go run
Current time 2024-06-27 21:25:29
Today's time 2024-06-27
Yesterday's time 2024-06-26
Time tomorrow 2024-06-28
Time 3 days ago 2024-06-24
Time 7 days ago 2024-06-20
1 hour ago
1 day ago
1 month ago

Time processing is a topic that can't be avoided no matter which programming language it is, we often do PHP development programmers, in order to learn the Go language more smoothly, the best way is to be able to find the same type of third-party libraries, to put it bluntly is to find a familiar and good use of the wheel, because people's hearts are always familiar with their own familiar things feel excited about something not familiar with something to be afraid of. Therefore, familiar things can reduce our learning difficulty and boost our self-confidence in learning. From the above two code examples, Go is not that difficult to learn, and it also breaks many people's claim that Go is very difficult to learn. Finally, to make it easier for you to learn the Carbon time manipulation tool, I've included the PHPnesbot/carbon and thegolang-module/carbon/v2 The official documentation is attached.

  • /
  • /golang-module/carbon/blob/master/

Welcome to follow, share, like, favorite, in the watch, I'm the author of WeChat public number "code farmer forefather".