# [Usage](../../../usage.md) > DateTime helper

Use `DateTimeHelper` when converting between user input, Carbon instances and database/display formats. Typical case: an [Input](../../components/forms/input.md) with `date` / `datetime-local` type renders Italian `dd/mm/yyyy` when the app locale is `it`, so convert it back before saving.

---

## Method

### `DateTimeHelper::formatForDB($date)`

Normalize a mixed value to a `Carbon` instance for DB usage. Accepts `DateTimeInterface`, ISO strings (`yyyy-mm-dd[ hh:mm[:ss]]`), IT strings (`dd/mm/yyyy[ hh:mm[:ss]]`, `/` or `-` separators), year-first slash variants and Unix timestamps. Returns `null` when unparsable.

```php
use KFramework\Helpers\DateTimeHelper;

$carbon = DateTimeHelper::formatForDB($request->input('birthday'));
// '31/12/2026 10:00:00' -> Carbon('2026-12-31 10:00:00')
// '2026-12-31'          -> Carbon('2026-12-31 00:00:00')
// garbage               -> null
```

### `DateTimeHelper::formatItalian($date, $time = true)`

Format a DB date to Italian display format. Pass `$time = false` for date-only `d/m/Y`.

```php
DateTimeHelper::formatItalian('2026-12-31 10:00:00');       // '31/12/2026 10:00:00'
DateTimeHelper::formatItalian('2026-12-31 10:00:00', false); // '31/12/2026'
DateTimeHelper::formatItalian('2026-12-31');                 // '31/12/2026'
```

### `DateTimeHelper::detectDateTimeFormat(string $value)` / `isValidDateTime(string $value)`

Strict round-trip detection of the input format (`Y-m-d`, `d/m/Y H:i:s`, `m/d/Y`, `YmdHis`, ISO `T` variants, ...). `detectDateTimeFormat()` returns the format string or `null`; `isValidDateTime()` returns `bool`.

```php
DateTimeHelper::detectDateTimeFormat('31/12/2026'); // 'd/m/Y'
DateTimeHelper::isValidDateTime('31/12/2026');      // true
DateTimeHelper::isValidDateTime('31/13/2026');      // false
```

---

## Output

- `formatForDB()`: `Carbon|null` — always check for `null` before saving.
- `formatItalian()`: `string` — formatted date, or the original value on failure.
- `detectDateTimeFormat()`: `string|null`; `isValidDateTime()`: `bool`.

---

## Example

```php
use KFramework\Helpers\DateTimeHelper;

// Save: IT input -> DB
$carbon = DateTimeHelper::formatForDB($request->input('starts_at'));

if (! $carbon) {
    return back()->with(['error' => 'Invalid date.']);
}

$event->starts_at = $carbon;
$event->save();

// Display: DB -> IT (same pattern used by the API credentials resource table)
$text = app()->getLocale() === 'it'
    ? DateTimeHelper::formatItalian($event->starts_at)
    : $event->starts_at->format('Y-m-d H:i:s');
```

## See also

- [Usage](../../../usage.md)
- [Input](../../components/forms/input.md) — `date` / `datetime-local` + `it` locale note
- [Form autofill](form_autofill.md) — prefill date fields from Eloquent records
