How to Parse Dates and Times from Conventional Input in PHP
Automating the process of parsing data from standard date & time string inputs can save us a lot of time.
Thankfully, using the ready-to-run PHP code examples below, we can easily take advantage of a free API designed for exactly this purpose.
This API will automatically parse standard date and time inputs into a detailed, easy-to-read response object that contains a timestamp in addition to the year, month, day, hour, minute, second, and day of the week referenced in the original string.
Let’s look at a quick example. Let’s say we get the following input from a United States user (note the country code must be specified to engage a country’s unique date & time formatting conventions):
{
"RawDateTimeInput": "06/04/2024",
"CountryCode": "US"
}
We’ll get the following result from processing this input:
{
"Successful": true,
"ParsedDateResult": "2024-06-04T00:00:00",
"Year": 2024,
"Month": 6,
"Day": 4,
"Hour": 0,
"Minute": 0,
"Second": 0,
"DayOfWeek": "Tuesday"
}
To structure our API call, we can begin by installing the client SDK with Composer. Let’s run the following command:
composer require cloudmersive/cloudmersive_validate_api_client
Next, let’s quickly shift our focus to authorization. We’ll need a free Cloudmersive API key to authorize our API calls (this will allow a limit of 800 API calls per month with no additional commitments).
Let’s now use the remaining code examples to call our date & time parsing function:
<?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\DateTimeStandardizedParseRequest(); // \Swagger\Client\Model\DateTimeStandardizedParseRequest | Input request
try {
$result = $apiInstance->dateTimeParseStandardDateTime($input);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling DateTimeApi->dateTimeParseStandardDateTime: ', $e->getMessage(), PHP_EOL;
}
?>
And that’s it — no more code required! Now we can easily take advantage of a powerful date & time parsing service in our PHP applications.