parfum/app/Helpers/DateTimeHelpers.php

99 lines
2.7 KiB
PHP

<?php
use Carbon\Carbon;
if (! function_exists('formatDate')) {
/**
* Format date/time with a configurable format using Carbon.
* Core formatting function used by formatTime() and formatDateTime().
*
* @param string $format Carbon format (default: 'l, d M Y')
* @param bool $translated Use translatedFormat for locale-aware output (default: true)
*/
function formatDate(?string $date = null, string $format = 'l, d M Y', bool $translated = true): string
{
if (! $date) {
return '-';
}
$carbon = Carbon::parse($date);
return $translated ? $carbon->translatedFormat($format) : $carbon->format($format);
}
}
if (! function_exists('formatTime')) {
/**
* Format time only (convenience wrapper for formatDate with time format).
*
* @param string $format Carbon format (default: 'H:i')
*/
function formatTime(?string $time = null, string $format = 'H:i'): string
{
return formatDate($time, $format, false);
}
}
if (! function_exists('formatDateTime')) {
/**
* Format date and time (convenience wrapper for formatDate with datetime format).
*
* @param string $format Carbon format (default: 'l, d M Y H:i:s')
*/
function formatDateTime(?string $dateTime = null, string $format = 'l, d M Y H:i:s'): string
{
return formatDate($dateTime, $format);
}
}
if (! function_exists('getAge')) {
/**
* Calculate age from birthdate using Carbon.
* Returns formatted string in Indonesian (e.g. "25 tahun 3 bulan").
*/
function getAge(?string $birthdate = null): string
{
if (! $birthdate) {
return '-';
}
$birth = Carbon::parse($birthdate);
$now = Carbon::now();
$diff = $birth->diff($now);
return "{$diff->y} tahun {$diff->m} bulan";
}
}
if (! function_exists('timeAgo')) {
/**
* Get relative time string using Carbon's diffForHumans().
* Returns localized relative time (e.g. "2 hours ago", "3 days ago").
*/
function timeAgo(?string $date = null): string
{
if (! $date) {
return '-';
}
return Carbon::parse($date)->diffForHumans();
}
}
if (! function_exists('normalizeOpeningHours')) {
/**
* Normalize opening hours for all days of the week.
* Ensures all 7 days are present in the result array.
*/
function normalizeOpeningHours(array $openingHours): array
{
$days = ['senin', 'selasa', 'rabu', 'kamis', 'jumat', 'sabtu', 'minggu'];
return collect($days)
->mapWithKeys(fn ($day) => [
$day => $openingHours[$day] ?? ['open' => null, 'close' => null],
])
->toArray();
}
}