Parsing Date & Time Information

Parsing date and time information from natural language input is a common requirement in various applications, such as event scheduling, reminders, or logging systems.

Instead of writing a lot of new code to achieve our goal, we’ll utilize a free API for date and time parsing. We can structure our API call using the ready-to-run PHP code examples provided below.

To understand “parsing” date and time information from natural language inputs, consider the following example. Given the text input:

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

We can parse this into a structured response with a timestamp and additional details:

{
  "Successful": true,
  "ParsedDateResult": "2024-07-27T17:00:00",
  "Year": 2024,
  "Month": 7,
  "Day": 27,
  "Hour": 17,
  "Minute": 0,
  "Second": 0,
  "DayOfWeek": "Saturday"
}

This response is based on the original API call made on Friday, July 26th, 2024.

To structure our API call, we start by installing the SDK with Composer:

composer require cloudmersive/cloudmersive_validate_api_client

Next, we need a free Cloudmersive API key to authorize our requests, allowing up to 800 API calls per month with no commitments.

Using the provided code examples, we can structure our request. Replace ‘YOUR_API_KEY’ with your 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 need! We can now handle unstructured text inputs with date and time references effectively.

Happy coding🚀🚀🚀
 
Live Chat

Hi! Do you need help?