A supplier emails "we'll ship the week after next". A contract PDF has six dates in it and exactly one of them is the renewal. A scanned form says "please return by August 14" with no year at all. You need a value you can put in a date column, and you need to know when you should not trust it.
Carbon::parse() handles none of that. An LLM asked for "the deadline" will hand you a date, sound certain, and be wrong about what day next Thursday is.
Split the reading from the arithmetic#
The trick that makes this reliable is refusing to let one system do both jobs.
strtotime() and Carbon are excellent at calendar arithmetic and completely useless at deciding which of six dates in a contract is the return deadline. A model is the exact reverse: good at reading intent off prose, bad at counting days. So ask the model only what the text says — this is a relative date, it names Thursday, it means next week — and do the counting in PHP.
Jev, TypeSafe's System One model, is built for that half. It answers typed questions with a probability distribution and a confidence, and it never writes free text. Asked "which weekday does this name?" it returns Thursday with a confidence of 0.94. It is never asked what date that is.
That split is why the pattern holds up. The model cannot be wrong about what day next Thursday is, because it is never asked.
Write the seven Choice questions#
Seven Choice questions cover every shape a date arrives in. mode says how it is written. The other six read the pieces, and your code only reads the pieces mode calls for — the same speculative fan-out I used for asking every question in one request.
Note the none option on every part. Documents routinely do not state the date you asked for, and without a hatch the model is forced into a wrong answer — the same reason I pair a Choice with a companion Noul elsewhere.
<?php
declare(strict_types=1);
namespace App\Support\Dates;
final class DateQuestions
{
private const ABSENT = 'The document does not state this, or it is not this kind of date.';
/** @var array<string, int> */
public const MONTHS = [
'January' => 1, 'February' => 2, 'March' => 3, 'April' => 4,
'May' => 5, 'June' => 6, 'July' => 7, 'August' => 8,
'September' => 9, 'October' => 10, 'November' => 11, 'December' => 12,
];
/** @var array<string, int> ISO weekday numbers, Monday = 1. */
public const WEEKDAYS = [
'Monday' => 1, 'Tuesday' => 2, 'Wednesday' => 3, 'Thursday' => 4,
'Friday' => 5, 'Saturday' => 6, 'Sunday' => 7,
];
/**
* @return array<string, array<string, mixed>>
*/
public static function for(string $role): array
{
return [
'mode' => [
'type' => 'choice',
'instructions' => "How is {$role} written? 'absolute' = a calendar date naming a "
."month (e.g. 'August 14', 'the 3rd of March'); 'relative' = given relative to "
."today (today, tomorrow, the day after tomorrow, or a named weekday such as "
."'next Thursday'); 'none' = the document does not state this date.",
'criteria' => ['absolute' => null, 'relative' => null, 'none' => null],
],
'month' => [
'type' => 'choice',
'instructions' => "If {$role} is an absolute calendar date, which month is it in?",
'criteria' => array_fill_keys(array_keys(self::MONTHS), null) + ['none' => self::ABSENT],
],
'day' => [
'type' => 'choice',
'instructions' => "If {$role} is an absolute calendar date, which day of the month (1-31)?",
'criteria' => array_fill_keys(array_map('strval', range(1, 31)), null) + ['none' => self::ABSENT],
],
'year' => [
'type' => 'choice',
'instructions' => "If {$role} is an absolute calendar date, which year? Pick 'none' "
."if the document states no year (code infers it), or 'out_of_range' if a year "
.'is stated but not in the list.',
// 151 years + 2 escapes. A Choice takes at most 255 options.
'criteria' => array_fill_keys(array_map('strval', range(1900, 2050)), null) + [
'out_of_range' => 'A year is stated for this date but is outside the listed range.',
'none' => 'No year is stated for this date.',
],
],
'day_anchor' => [
'type' => 'choice',
'instructions' => "If {$role} is relative to today, which day is it? 'today', "
."'tomorrow', 'day_after' (the day after tomorrow), or 'weekday' (a named day "
.'of the week).',
'criteria' => [
'today' => null, 'tomorrow' => null, 'day_after' => null,
'weekday' => null, 'none' => self::ABSENT,
],
],
'weekday' => [
'type' => 'choice',
'instructions' => "If {$role} names a day of the week, which one?",
'criteria' => array_fill_keys(array_keys(self::WEEKDAYS), null) + ['none' => self::ABSENT],
],
'week_offset' => [
'type' => 'choice',
'instructions' => "If {$role} names a weekday, which week is it in? 'next' for "
."'next Thursday' or 'Thursday next week'; 'current' for 'this Thursday'; "
."'none' for a bare weekday with no qualifier (just 'Thursday' / 'on Thursday').",
'criteria' => ['current' => null, 'next' => null, 'none' => self::ABSENT],
],
];
}
}
The $role string is the whole design. Pass "the deadline to return the form", not "the date". A contract contains an effective date, an expiry, a notice period and a signature date, and "the date" makes the model guess which one you meant. A named role makes the answer checkable by a human in two seconds.
Send the questions in one request#
There is no PHP SDK, so this is Laravel's HTTP client against POST /v1/systemone. One call, seven questions, one set of token costs.
<?php
declare(strict_types=1);
namespace App\Support\Dates;
use Illuminate\Support\Facades\Http;
final readonly class Jev
{
public function __construct(
private string $apiKey,
// Pin the version. Calibration shifts between releases.
private string $model = 'jev-1.14.0',
) {}
/**
* @param array<string, array<string, mixed>> $questions
* @return array<string, array<string, mixed>>
*/
public function ask(string|array $state, array $questions): array
{
return Http::withToken($this->apiKey)
->timeout(30)
->retry(3, fn (int $attempt): int => $attempt * 250)
->post('https://api.typesafe.ai/v1/systemone', [
'model' => $this->model,
'state' => $state,
'questions' => $questions,
])
->throw()
->json('answers');
}
}
Each answer comes back keyed by the question name, carrying the selected option, a probability for every option and a confidence:
{
"answers": {
"mode": {
"type": "choice",
"choice": "relative",
"confidence": 0.93,
"probabilities": { "absolute": 0.03, "relative": 0.95, "none": 0.02 }
},
"weekday": {
"type": "choice",
"choice": "Thursday",
"confidence": 0.94,
"probabilities": { "Thursday": 0.95, "Friday": 0.02, "none": 0.01 }
},
"week_offset": {
"type": "choice",
"choice": "next",
"confidence": 0.71,
"probabilities": { "current": 0.14, "next": 0.82, "none": 0.04 }
}
},
"usage": { "input_tokens": 1180, "output_tokens": 21 }
}
Not a single date anywhere in that payload. Good.
Resolve the parts into a date in PHP#
Now the arithmetic, against an injected "today" rather than the wall clock. Injecting it is what makes the whole thing testable, and it is one more reason to standardise on CarbonImmutable over mutable Carbon — every branch below returns a new instance instead of quietly mutating the one you passed in.
<?php
declare(strict_types=1);
namespace App\Support\Dates;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
final readonly class ResolvedDate
{
public function __construct(
public ?CarbonImmutable $date,
public ?float $confidence,
public bool $needsReview,
public string $note = '',
) {}
}
final readonly class DateResolver
{
public function __construct(
private CarbonImmutable $today,
private float $reviewBelow = 0.60,
) {}
/**
* @param array<string, array<string, mixed>> $answers
*/
public function resolve(array $answers): ResolvedDate
{
$mode = $answers['mode']['choice'];
// Only the parts this shape actually consumes count towards confidence.
$used = [(float) $answers['mode']['confidence']];
return match ($mode) {
'none' => $this->result(null, $used, 'no such date stated'),
'absolute' => $this->absolute($answers, $used),
'relative' => $this->relative($answers, $used),
default => $this->result(null, $used, "unrecognised mode: {$mode}"),
};
}
/**
* @param array<string, array<string, mixed>> $answers
* @param list<float> $used
*/
private function absolute(array $answers, array $used): ResolvedDate
{
[$month, $day, $year] = [
$answers['month']['choice'],
$answers['day']['choice'],
$answers['year']['choice'],
];
$used[] = (float) $answers['month']['confidence'];
$used[] = (float) $answers['day']['confidence'];
$used[] = (float) $answers['year']['confidence'];
if (! isset(DateQuestions::MONTHS[$month]) || ! ctype_digit($day)) {
return $this->result(null, $used, 'absolute date incomplete');
}
// A year is stated but outside the option list. Flag it, never guess it.
if ($year === 'out_of_range') {
return $this->result(null, $used, 'year outside 1900-2050');
}
$month = DateQuestions::MONTHS[$month];
$day = (int) $day;
if ($year === 'none') {
// No year stated: assume this one, roll forward only if well past.
$resolved = $this->make($this->today->year, $month, $day);
if ($resolved === null) {
return $this->result(null, $used, "impossible date: {$month}/{$day}");
}
if ($resolved->lt($this->today->subDays(31))) {
$resolved = $this->make($this->today->year + 1, $month, $day);
}
return $this->result($resolved, $used, '');
}
$resolved = $this->make((int) $year, $month, $day);
return $resolved === null
? $this->result(null, $used, "impossible date: {$year}-{$month}-{$day}")
: $this->result($resolved, $used, '');
}
/**
* @param array<string, array<string, mixed>> $answers
* @param list<float> $used
*/
private function relative(array $answers, array $used): ResolvedDate
{
$anchor = $answers['day_anchor']['choice'];
$used[] = (float) $answers['day_anchor']['confidence'];
if ($anchor === 'weekday') {
$weekday = $answers['weekday']['choice'];
$offset = $answers['week_offset']['choice'];
$used[] = (float) $answers['weekday']['confidence'];
$used[] = (float) $answers['week_offset']['confidence'];
if (! isset(DateQuestions::WEEKDAYS[$weekday])) {
return $this->result(null, $used, 'relative weekday not read');
}
return $this->result($this->weekday($weekday, $offset), $used, '');
}
return match ($anchor) {
'today' => $this->result($this->today, $used, ''),
'tomorrow' => $this->result($this->today->addDay(), $used, ''),
'day_after' => $this->result($this->today->addDays(2), $used, ''),
default => $this->result(null, $used, 'relative day not read'),
};
}
/**
* A bare weekday is the next occurrence on or after today; 'next' is the
* following calendar week; 'current' is this week. State the convention,
* because "next Thursday" means two different days to two different people.
*/
private function weekday(string $weekday, string $offset): CarbonImmutable
{
$iso = DateQuestions::WEEKDAYS[$weekday];
$monday = $this->today->startOfWeek(CarbonInterface::MONDAY);
return match ($offset) {
'next' => $monday->addDays(7 + $iso - 1),
'current' => $monday->addDays($iso - 1),
default => $this->today->addDays(($iso - $this->today->isoWeekday() + 7) % 7),
};
}
private function make(int $year, int $month, int $day): ?CarbonImmutable
{
// 31 September is a confident-looking set of parts that is not a date.
return checkdate($month, $day, $year)
? CarbonImmutable::create($year, $month, $day)->startOfDay()
: null;
}
/**
* @param list<float> $used
*/
private function result(?CarbonImmutable $date, array $used, string $note): ResolvedDate
{
$confidence = $used === [] ? null : min($used);
$needsReview = $date === null || $confidence === null || $confidence < $this->reviewBelow;
return new ResolvedDate($date, $confidence, $needsReview, $note);
}
}
Gate the date on its weakest part#
The important line in that class is min($used).
A date assembled from four parts is only as good as the shakiest one. The month can come back at 0.99 and the year at 0.41, and the resulting date is a coin flip dressed as a fact. Taking the minimum across only the parts that shape actually consumed is the honest summary — and it means an uncertain week_offset on "next Thursday" sends the whole thing to review even though the weekday was read perfectly.
Confidence here is not a probability. It is a measure of how concentrated the distribution is across the options: 1.0 when all of it sits on one option, 0 when it is spread evenly. For a Choice with n options it is (p_max - 1/n) / (1 - 1/n). Only the top probability counts, so (0.6, 0.3, 0.1) and (0.6, 0.2, 0.2) both score 0.4.
Start at 0.60 and tune it against your own documents. The right threshold scales with what acting on a wrong date costs you — the same risk-weighted gating I use for confidence-gated intent routing, where a read-only action clears at 0.5 and a destructive one needs 0.9.
Two cases always go to review regardless of the number:
modecame backnone. The document does not state that date. There may well be other dates in it; none of them are the one you asked for.- The parts did not assemble.
absolute date incomplete,year outside 1900-2050,impossible date. The model was confident about pieces that do not make a date, which is exactly when you want a human.
Validate the resolved date before you store it#
Confidence catches an uncertain read. It does not catch a confident read of something that makes no sense in your domain. Add a second pass in code:
<?php
declare(strict_types=1);
namespace App\Support\Dates;
use Carbon\CarbonImmutable;
final readonly class DatePlausibility
{
public function __construct(private CarbonImmutable $today) {}
/**
* @return list<string> Empty when the date is plausible.
*/
public function check(ResolvedDate $resolved, bool $isDeadline): array
{
if ($resolved->date === null) {
return [];
}
$problems = [];
// A contract date 40 years out is almost always a misread year.
if ($resolved->date->gt($this->today->addYears(10))) {
$problems[] = 'more than ten years in the future';
}
if ($resolved->date->lt($this->today->subYears(10))) {
$problems[] = 'more than ten years in the past';
}
// Something described as a deadline that has already passed is worth a look.
if ($isDeadline && $resolved->date->lt($this->today)) {
$problems[] = 'deadline resolved into the past';
}
return $problems;
}
}
That last check earns its keep on documents with no stated year. "Return by August 14" read in November resolves to next August under the roll-forward rule, which is usually right and occasionally very wrong.
Run the extraction in a queued job#
A seven-question call takes a second or two. That belongs off the request cycle, in a job, for the same reasons any agent run belongs in the queue.
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Document;
use App\Support\Dates\DateQuestions;
use App\Support\Dates\DateResolver;
use App\Support\Dates\Jev;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;
final class ExtractDocumentDate implements ShouldQueue
{
use Queueable;
public int $tries = 3;
public function __construct(
public Document $document,
public string $role = 'the deadline to return the form',
) {}
public function handle(Jev $jev): void
{
$answers = Cache::remember(
// Same text and same role means the same answers. Never pay twice.
'jev:date:'.hash('xxh128', $this->document->body.'|'.$this->role),
now()->addDays(30),
fn (): array => $jev->ask(
['document' => $this->document->body, 'looking_for' => $this->role],
DateQuestions::for($this->role),
),
);
// CarbonImmutable::now() respects travelTo() in tests.
$resolved = (new DateResolver(CarbonImmutable::now()->startOfDay()))->resolve($answers);
$this->document->forceFill([
'deadline_at' => $resolved->date,
'deadline_confidence' => $resolved->confidence,
'needs_review' => $resolved->needsReview,
'review_note' => $resolved->note,
])->save();
}
}
deadline_at is a nullable date column and needs_review is a boolean. The review screen reads better if you also store the sentence the date came from — ask for it with a separate Choice over the document's lines, or fall back to showing the whole document with the model's probabilities beside each part so the reviewer can see what the close second was.
Pin today in your tests#
"Next Thursday" is a moving target, which makes it exactly the thing you want frozen in CI. Two fakes do it: travelTo() pins the clock, Http::fake() pins the answers.
<?php
declare(strict_types=1);
use App\Support\Dates\DateResolver;
use App\Support\Dates\Jev;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Http;
function jevAnswer(string $choice, float $confidence): array
{
return ['type' => 'choice', 'choice' => $choice, 'confidence' => $confidence];
}
it('resolves next Thursday against a pinned today', function () {
// 30 July 2026 is itself a Thursday, which is the interesting case.
$this->travelTo(CarbonImmutable::parse('2026-07-30'));
Http::fake(['api.typesafe.ai/*' => Http::response([
'model' => 'jev-1.14.0',
'answers' => [
'mode' => jevAnswer('relative', 0.93),
'day_anchor' => jevAnswer('weekday', 0.91),
'weekday' => jevAnswer('Thursday', 0.94),
'week_offset' => jevAnswer('next', 0.71),
],
'usage' => ['input_tokens' => 1180, 'output_tokens' => 21],
])]);
$answers = app(Jev::class)->ask('Let\'s schedule the design review for next Thursday.', []);
$resolved = (new DateResolver(CarbonImmutable::now()->startOfDay()))->resolve($answers);
expect($resolved->date->toDateString())->toBe('2026-08-06')
->and($resolved->confidence)->toBe(0.71) // the weakest part, not the strongest
->and($resolved->needsReview)->toBeFalse();
});
it('sends an impossible date to review', function () {
$this->travelTo(CarbonImmutable::parse('2026-07-30'));
$answers = [
'mode' => jevAnswer('absolute', 0.96),
'month' => jevAnswer('September', 0.95),
'day' => jevAnswer('31', 0.88),
'year' => jevAnswer('2027', 0.92),
];
$resolved = (new DateResolver(CarbonImmutable::now()->startOfDay()))->resolve($answers);
expect($resolved->date)->toBeNull()
->and($resolved->needsReview)->toBeTrue()
->and($resolved->note)->toContain('impossible date');
});
Record the fixtures once against the live API, then run offline forever. Keep a dozen real documents with hand-checked answers as a separate golden set, run on a schedule rather than in CI: the offline tests guard the arithmetic, the golden set tracks accuracy drift when you move the pinned model version.
Avoid the five ways relative dates go wrong#
Two plausible deadlines in one document. The role string is your only lever. "The deadline to return the signed form" beats "the deadline", and if the document genuinely has two, split it into two calls with two roles rather than hoping one answer covers both.
Day/month ordering. "03/04/2027" is 3 April in Glasgow and 4 March in Chicago. The model reads the convention from surrounding context when there is any, and guesses when there is not — which shows up as a flat distribution across month and a low confidence. That is the gate doing its job, not failing.
Fiscal years. "Due at the end of Q3" is not a date at all until you know whose Q3. Resolve it in code from the tenant's fiscal calendar, and keep it out of the question set.
Timezones. Everything here returns a date, not an instant. The moment you store it in a datetime column, a 2026-08-06 deadline becomes 2026-08-06 00:00 in some zone, and a user in Sydney sees the 5th. Keep the column a date unless you genuinely have a time.
Dates inside quoted correspondence. A reply chain carries the original email's dates under it. Trim to the top message before building the state, or you will confidently extract last month's deadline.
Wrapping Up#
Build the questions, resolve in PHP against an injected today, take the minimum confidence across the parts you used, and validate for plausibility before you store. The model reads, your code counts, and the cases where that is not enough announce themselves instead of landing silently in a date column.
If you are extracting other values from the same documents, regex candidates with a Jev pick does for amounts and reference numbers what this does for dates. And when the question is which action a document should trigger rather than what it says, confidence-gated intent routing is the next piece.
FAQ#
How do I extract a date from free text in PHP?
Separate finding the date from calculating it. Use a model to read the parts the text states — whether it is absolute or relative, which month, day, year or weekday it names — and then assemble those parts into a CarbonImmutable in your own code. strtotime() and Carbon::parse() are reliable at arithmetic but have no way to decide which of several dates in a document is the one you asked for, which is exactly the job a Choice question does well.
Can Carbon parse natural language dates like "next Thursday"?
Carbon passes strings through PHP's strtotime(), which does understand a small set of English phrases including "next Thursday" and "tomorrow". The catch is that it only works on an isolated, well-formed phrase: hand it a paragraph of prose and it returns false or, worse, latches onto the wrong fragment. It also has its own opinion about what "next Thursday" means, which may not match yours. Extract the parts first, then let Carbon do the arithmetic you control.
Why not just send the whole document to an LLM and ask for a date?
Because you get a date-shaped string with no reliable signal about whether it is right. The model may pick a different clause than you meant, get the weekday arithmetic wrong, or invent a date the document never states — all with the same confident tone. Asking for the parts instead gives you a probability distribution per part, so a weak read announces itself and can be routed to a human rather than written to your database.
What is a Choice question in TypeSafe's System One API?
A Choice asks the model to select one option from a set you define, up to 255 options. The answer contains the selected option, a probability for every option, and a confidence value from 0 to 1 derived from how concentrated that distribution is. Because the options are a closed set built by your code, the model cannot return a value that was not on the list — which is what makes the answer safe to branch on directly.
How do I handle ambiguous or missing years?
Give the year question an explicit none option meaning "the text states no year" and an out_of_range option meaning "a year is stated but it is not in my list". When the answer is none, infer the year in code: assume the current one and roll forward to the next only when the resulting date is already well past, which handles "return by August 14" read in September. When it is out_of_range, flag the document for review rather than guessing.
How do I test date extraction deterministically?
Pin both the clock and the API. Laravel's travelTo() freezes "now" so a relative date resolves to the same day on every run, and Http::fake() replays a recorded response so no request leaves CI. Record real responses once as fixtures, assert on the resolved date and the confidence, and keep a separate golden set of real documents that runs on a schedule to catch accuracy drift when you change the pinned model version.