How to Parse Date & Time Info from Natural Language Input in PHP

Cloudmersive
2 min readJun 4, 2024

We can easily parse natural language date & time strings into neatly formatted data using just a few lines of PHP code.

Rather than write a bunch of new code to accomplish our goal, we’ll simply call a free API to handle date & time parsing for us. We can easily structure our API call using the complementary, ready-to-run PHP code examples provided further down the page.

To better understand what we mean by “parsing” date and time information from natural language inputs, let’s look at a quick example. Let’s say we get the following text input:

{
"RawDateTimeInput": "tomorrow at 3pm"
}

We can parse this value into a structured response that includes a timestamp and several additional fields of information:

{
"Successful": true,
"ParsedDateResult": "2024-06-05T15:00:00",
"Year": 2024,
"Month": 6,
"Day": 5,
"Hour": 15,
"Minute": 0,
"Second": 0,
"DayOfWeek": "Wednesday"
}

This date and time response is generated relative to the original API call, which occurred on Tuesday, June 4th, 2024.

To structure our API call, we can start by installing the SDK. Let’s run the following command to install with Composer:

composer require cloudmersive/cloudmersive_validate_api_client

Next, let’s turn our attention to authorization. We’ll need a free Cloudmersive API key to authorize our requests (this will allow us to make a limit of 800 API calls per month with zero commitments).

Finally, we can use the remaining code examples to structure our request. We can replace ‘YOUR_API_KEY’ with our own API key string:

<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');



$apiInstance = new Swagger\Client\Api\DateTimeApi(


new GuzzleHttp\Client(),
$config
);
$input = new \Swagger\Client\Model\DateTimeNaturalLanguageParseRequest(); // \Swagger\Client\Model\DateTimeNaturalLanguageParseRequest | Input request

try {
$result = $apiInstance->dateTimeParseNaturalLanguageDateTime($input);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling DateTimeApi->dateTimeParseNaturalLanguageDateTime: ', $e->getMessage(), PHP_EOL;
}
?>

That’s all the code we’ll need! Now we can make the most of unstructured text inputs with date & time references.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.