How to Manage Dates and Times in PHP Using Carbon

Date and time manipulation is one of a few frequently-experienced challenges of developing web apps in PHP. And one of it’s most prevalent issues is identifying time disparities and making them readable, such as “one hour ago”.

However, handling dates and times — and issues such as this — is greatly simplified by using Carbon; it’s a library which reduces lengthy hours of coding and debugging to only a few lines of code. This is because Carbon, created by Brian Nesbit, extends PHP’s own DateTime class and makes it much simpler to use.

If you’ve not heard of it before, it is self-described as:

A basic PHP API extension for DateTime

In this tutorial, you will learn Carbon’s core features and capabilities, giving you the ability to far more easily manipulate date and time in PHP.



Prerequisites

To follow this tutorial you need the following components:

  • PHP 7.4 or higher.
  • Composer globally installed.



Installation

To install Carbon, first create a new project directory called carbon, change into the directory, and install the package, by executing the following commands:

mkdir carbon
cd carbon
composer require nesbot/carbon

!!!tip

Carbon is already included if you’re using Laravel. If you are, have a look at the suggested Laravel settings and best practices. If you’re using Symfony, have a look at the Symfony configuration and best-practices guidelines.

!!!tip



Format dates using Carbon

With Carbon installed, in your editor or IDE, create a new PHP file, named index.php in the root of your project directory. Then, add the code below to index.php to include Composer’s Autoloader file, vendor/autoload.php, and imported Carbon’s core class_._

<?php 
require 'vendor/autoload.php';
use CarbonCarbon;



Print dates

Now that Carbon’s installed, let’s start working through some examples, starting with the most essential: printing out some dates. To do that, we’ll use carbon::today to retrieve today’s date via Carbon, which you can see in the example below.

<?php

require __DIR__ . "/vendor/autoload.php";

echo carbon::today() . "n";

Add that to index.php and then run it.

2021-10-25 00:00:00

The output, which you can see an example of above, returns the current date, with the time being blank. However, if you update index.php to use carbon:: now instead, which you can see in the example below, you can retrieve the time along with the date.

<?php

require __DIR__ . "/vendor/autoload.php";

$now = carbon::now()
echo "$nown";

After updating index.php and running it, you should see output similar to the example below, in your terminal.

2021-01-25 22:49:56

In contrast to Carbon::now() which returns the current date and time, and Carbon:today() which only returns the current date, Carbon::yesterday() and Carbon::tomorrow() generate Carbon instances for yesterday and tomorrow, respectively, as in the examples below.

<?php

require __DIR__ . "/vendor/autoload.php";

$yes = Carbon::yesterday();
echo "Yesterday: $yesn";

$tomorrow = Carbon::tomorrow();
echo "Tomorrow: $tomorrown";

The functions today(), yesterday(), now, and tomorrow() are examples of common static instantiation helpers.



Create dates with precision

Carbon also allows us to generate dates and times based on a set of parameters. For example, to create a new Carbon instance for a specific date use the Carbon::createFromDate() method, passing in the year, month, day, and timezone, as in the following example.

<?php

require __DIR__ . "/vendor/autoload.php";

$year = 2020;
$month = 08;
$day = 21;
$timezone = 'Europe/Berlin';
Carbon::createFromDate($year, $month, $day, $timezone);

You can also specify the time, by calling Carbon::create(), passing in the year, month, day, timezone, hour, minute, and second, as in the following example

<?php

require __DIR__ . "/vendor/autoload.php";

$year = 2021;
$month = 04;
$day = 21;
$timezone = 'Europe/Berlin';
$hour = 11;
$minute = 11;
$second = 11;
Carbon::create($year, $month, $day, $hour, $minute, $second, $timezone);

If any one or more of $year, $month, $day, $hour, $minute, or $second are set to null their now() equivalent values will be used. If $hour is not null, however, then the default values for $minute and $second will be 0.

If you pass in null for any of those attributes, it will default to the current date and time.

Update index.php in your editor or IDE to match the code below and run it.


<?php

require __DIR__ . "/vendor/autoload.php";

use CarbonCarbon;

$date1 = Carbon::create(2021,10, 25, 12, 48, 00);
echo $date1 . "n";

$date2 = Carbon::create(2021, 8, 25, 22, 48, 00, 'Europe/Moscow');
echo $date2 . "n";

$date3 = Carbon::createFromDate(2018, 8, 14, 'America/Chicago');
echo $date3 . "n";

$date4 = Carbon::createFromDate(2021,10, 25, 'Africa/Lagos');
$date5 = Carbon::createFromTimestamp(1633703084);
echo $date5. "n";

The create() function in the first variable creates a Carbon instance from date and time components; A timezone was supplied on the constructor to the second variable.

A Carbon object was constructed using date components with Carbon::createFromDate() when initializing the third and fourth variables. Doing so generates a Carbon instance based on just on a date.

It’s worth pointing out that if no timezone is specified, your default timezone is used. However, if a timezone other than yours is specified, the timezone’s actual time is supplied. The current time is set in the time section.

The final variable, initialized using Carbon::createFromTimestamp, generates a date based on a timestamp.



Relative Modifiers

Another fantastic feature of Carbon is relative modifiers. These allow strings such as “next friday” or “a year ago” to be used when constructing Carbon instances relative to the current date.

The following are examples of strings that are considered relative modifiers.

  • +
  • -
  • ago
  • first
  • next
  • last
  • this
  • today
  • tomorrow

    Modify the date and time

When working with dates, you’ll need to do more than just get the date and time. You’ll frequently need to modify the date or time as well, such as adding a day or a week or subtracting a month.

A good example of needing this functionality is when building an affiliate program. In this scenario you’ll want the affiliate cookie which the user receives to expire after a specified period of time, making the referral invalid.

Let’s assume a cookie has a 90-day lifespan. With Carbon’s add and subtract methods, we could compute that time quite trivially. The example below uses addDays() to determine when the cookie expires.

<?php

require __DIR__ . "/vendor/autoload.php";

$name = 'Affliate_Program';
$value = 'Referrer ID';
$path = '/';
$current = Carbon::now();

// add 90 days to the current time
$time = $current->addDays(90);
$expires = strtotime($time);
setcookie($name, $value, $expires, $path);

It also uses some of the other add() and sub() methods which Carbon provides. If you’re adding a single date, such as a day, you use addDay(), but if you’re adding several days, you use addDays(). Using Carbon’s add and subtract methods can provide you with adjusted date and times.



Looking forward and back

Carbon also provides the next() and previous() functions which return the upcoming and previous occurrences of a particular weekday, which you can see an example of in the code below.

<?php

require __DIR__ . "/vendor/autoload.php";

use CarbonCarbon;

$now = Carbon::now();
echo "$nown";

$next_monday = $now->next(Carbon::MONDAY);
echo "Next monday: $next_mondayn";

$prev_monday = $now->previous(Carbon::MONDAY);
echo "Previous monday: $prev_mondayn";



Format the date and time

Yet another fantastic option Carbon provides is the ability to format dates and times in whatever format that you desire.

As Carbon is an expanded version of PHP’s built-in date and time functions, Carbon can use PHP’s built-in date formats via the format() function. In addition, toXXXString() methods are available to display dates and times with predefined formatting.

<?php

require __DIR__ . "/vendor/autoload.php";

$dt = Carbon::create(2021,10, 25, 12, 48, 00);
echo $dt->toDateString();//2021-10-25
echo $dt->toFormattedDateString();//Oct 25, 2021
echo $dt->toTimeString();//12:48:00
echo $dt->toDateTimeString();//2021-10-25 12:48:00
echo $dt->toDayDateTimeString();//Mon, Oct 25, 2021 12:48 PM
echo $dt->format('Y-m-d h:i:s A');//2021-10-25 12:48:00 PM

Other typical datetime formatting methods available to Carbon include the following.

<?php

require __DIR__ . "/vendor/autoload.php";

$dt->toAtomString();
$dt->toCookieString();
$dt->toIso8601String();
$dt->toIso8601ZuluString();
$dt->toRfc822String();
$dt->toRfc850String(); 
$dt->toRfc1036String();
$dt->toRfc1123String();
$dt->toRfc3339String(); 
$dt->toRfc7231String(); 
$dt->toRssString();
$dt->toW3cString(); 



Calculate relative time

The diffForHumans() functions in Carbon also allow us to represent time in relative terms. Datetime discrepancies are frequently displayed in a so-called humanized format, such as in one year or three minutes ago.

Let’s assume we’re developing an extension for a blog CMS and we want to display the article’s publish time in “hours ago” or the comments publish time in “hours ago.”

First, the time and date the article was published, as well as other parameters, would be recorded in a database field. As a result, we extract the date from the database in the format Y-m-d H:i:s and store it in a variable. Let’s call it $time.


<?php

$time = $row['articledate']; 

If the date in our database is August 4th, 2021, such as in the example below, you would use the carbonCreateFromFormat() function to produce a Carbon date, and then use diffForHumans() to find the difference.

<?php

require __DIR__ . "/vendor/autoload.php";

$row['articledate'] = 2021-08-04 16:19:49;
$dt = Carbon::createFromFormat('Y-m-d H:i:s', $time);

echo $dt->diffForHumans() . "n";

If the date was saved as a timestamp, you can call Carbon::createFromTimestamp. Carbon also provides user translator services. So if your site makes use of a user’s language preferences, call the language. If you have a user that speaks French, for example, all you have to do is call the function before the code, as seen below.

<?php

require __DIR__ . "/vendor/autoload.php";

Carbon::setLocale()'.Carbon::setLocale('fr');
echo $dt->diffForHumans() . "n";

Output in this case would be, for example, ‘il y a 2 mois’.



That’s the essentials of managing dates and times in PHP using Carbon

In this tutorial, you learned how to install Carbon and its core functionality. However, Carbon has a great deal more functionality than has been covered in this tutorial. Check out their docs if you’re keen to learn more about the available functionality.


Source link

Some Awesome APIs for your next project



Some Awesome APIs for your next project

Several free web APIs are available to connect to your mobile app, web app, or website to add compelling functionality.

A web API is an application programming interface that may be accessed through the internet using web-specific protocols.

Here are nine APIs to create some fantastic projects:

1. The CheapShark API

CheapShark is a service that monitors the pricing of PC games on sites such as Amazon, Steam, and GamersGate and displays the best discounts to customers. Users may check for top bargains, search for the lowest price on a specific game, sign up for notifications, or browse what’s available on the site. Developers may use the CheapShark API to incorporate the site’s pricing data into their websites or apps.

linkCheapShark API

2. The Wit.AI

Turn text or speech into recognizable actions that your app/website can use.

Wit.ai is an interface for natural language processing (NLP) that converts natural language (voice or text communications) into structured data. Wit is used by developers because it streamlines creating apps and gadgets with which users can speak. Developers would have to master natural language processing methods without it. That would take too much time if you only wanted to create a simple application.

linkWit.ai API

3. GrammarBot API

The GrammarBot API offers spelling and grammatical checks to your application. Submit the text, and you’ll get a JSON response with potential issues and suggested fixes.

linkGrammarBot API

4. Rapid API

Based only on APIs, this is a handy tool. It’s more than simply an API directory; it’s also an API marketplace. If you’ve created an API and want to charge others to use it, you can publish it on RapidAPI.

If you only want to utilize APIs, RapidAPI provides an API playground to test an API in several languages! It is pretty beneficial.

linkRapid API

Thanks for reading!

I hope it motivates you to build more amazing projects, acquire confidence, and grow as a developer!

Follow me on Github and Twitter




Source link

Week 1 task-force-3 – DEV Community

This week was good because I made new friends and mates which is the coolest thing in this week ever.
On my first day, We had a game of putting an egg on top of the bottle which was tough, but we did it.
We had a good introduction from both awesomity and code of africa team members. It was my first time to do a 16 personalities test which made me discover and realize many things about me.

Let’s talk about soft skills, we learned many things including presentation delivering, communication,… In the presentation, It was a little bit challenging because we knew that actual presentation slides occupy 7% of what remains in the audience’s mind.
In communication we learnt that a good one has 3 parts: intro,main, end and at the end of each part there should be a question. We had many examples and plays related to that topic which was cool.

What about coding skills, we learnt about user stories which are a unit of agile framework about explaining features from the user’s perspective. I was able to build user stories related to my app(Yombi app) which made me realize that there are many things to change.
We learnt to build the best front end pages related to user stories we’ve developed.

Did you have fun with the team ? Yeah, on Friday afternoon, we had a game with awesomity team which was the funniest thing ever. After the game,everyone was saying : Oooooh my ribs !!!!!!!. We beat an awesome team which was tough to win against an experienced team. We had drinks and chocolate to eat. Funny thing was that I was the only one who drank soda, others were drinking beers except me which amazed me so much.

What I expect at the end of this 6 weeks program, I want to be not only good but best front end developer who can work in any team across the world, I want to get paid so that I can support my startup growth, I believe that one time I will be sharing stories of how I built my startup to be the best not only in Africa but in the world.


Source link