I am creating a project to create journal entries for TTRPG games. We play in a few different settings and I want to incorporate an in world date for entries. I want to create an object that can share logic between the Vue components and the Laravel API, but I don’t really need to send the object itself back and forth, just the string representation of the in-world date. Is there a good way to share the logic for the date class between the front end and the backend without having to make requests for every manipulation of the date?
Here is the mostly untested date object I created on the backend:
class CustomDate
{
public Calendar $calendar;
public Era $era;
public int $year;
public Month $month;
public Day $day;
public int $dayNum;
public int $hour;
public int $minute;
public int $second;
public int $millisecond;
/**
* @param Calendar $calendar
* @param string|null $dateString
* @param string $format
*/
public function __construct(Calendar $calendar, string $dateString = null, string $format = 'gg-y-M-d')
{
$this->calendar = $calendar;
$dateString ??= $calendar->default_date;
CustomDate::setFromFormattedString($this, $dateString, $format);
}
/**
* This allows a string to set the date
* <ul>
* <li>d = numerical day of month with no leading 0</li>
* <li>dd = numerical day of month with leading 0</li>
* <li>ddd = first three letters of the day name</li>
* <li>dddd = full day name</li>
* <li>f = 1/10 of a second includes trailing 0</li>
* <li>ff = 1/100 of a second includes trailing 0</li>
* <li>fff = 1/1000 of a second includes trailing 0</li>
* <li>F = 1/10 of a second no trailing 0</li>
* <li>FF = 1/100 of a second no trailing 0</li>
* <li>FFF = 1/1000 of a second no trailing 0</li>
* <li>g = sequence number of era</li>
* <li>gg = abbreviation or era</li>
* <li>ggg = full era name</li>
* <li>h = 12-hour clock format no leading 0</li>
* <li>hh = 12-hour clock format with leading 0</li>
* <li>H = 24-hour clock format no leading 0</li>
* <li>HH = 24-hour clock format with leading 0</li>
* <li>m = minute 0-59 with no leading 0</li>
* <li>mm = minute 0-59 with leading 0</li>
* <li>M = month number with no leading 0</li>
* <li>MM = month number with leading 0</li>
* <li>MMM = month abbreviation</li>
* <li>MMMM = full month name</li>
* <li>s = second 0-59 with no leading 0</li>
* <li>ss = second 0-59 with leading 0</li>
* <li>t = A or P for AM/PM designation</li>
* <li>tt = AM or PM</li>
* <li>y = year with no leading zeros</li>
* <li>y..y = year with leading digits needed to ensure minimum digits equals number of y characters</li>
* </ul>
*
* @param string $dateString
* @param string $format
* @return void
*/
public function setDate(string $dateString, string $format = 'gg-y-M-d'): void
{
CustomDate::setFromFormattedString($this, $dateString, $format);
}
/**
* This returns a formatted string of the date, the default format is 'gg-yyy-M-d'
* <ul>
* <li>d = numerical day of month with no leading 0</li>
* <li>dd = numerical day of month with leading 0</li>
* <li>ddd = first three letters of the day name</li>
* <li>dddd = full day name</li>
* <li>f = 1/10 of a second includes trailing 0</li>
* <li>ff = 1/100 of a second includes trailing 0</li>
* <li>fff = 1/1000 of a second includes trailing 0</li>
* <li>F = 1/10 of a second no trailing 0</li>
* <li>FF = 1/100 of a second no trailing 0</li>
* <li>FFF = 1/1000 of a second no trailing 0</li>
* <li>g = sequence number of era</li>
* <li>gg = abbreviation or era</li>
* <li>ggg = full era name</li>
* <li>h = 12-hour clock format no leading 0</li>
* <li>hh = 12-hour clock format with leading 0</li>
* <li>H = 24-hour clock format no leading 0</li>
* <li>HH = 24-hour clock format with leading 0</li>
* <li>m = minute 0-59 with no leading 0</li>
* <li>mm = minute 0-59 with leading 0</li>
* <li>M = month number with no leading 0</li>
* <li>MM = month number with leading 0</li>
* <li>MMM = month abbreviation</li>
* <li>MMMM = full month name</li>
* <li>s = second 0-59 with no leading 0</li>
* <li>ss = second 0-59 with leading 0</li>
* <li>t = A or P for AM/PM designation</li>
* <li>tt = AM or PM</li>
* <li>y = year with no leading zeros</li>
* <li>y..y = year with leading digits needed to ensure minimum digits equals number of y characters</li>
* </ul>
*
* @param string $format
* @return string
*/
public function getDateString(string $format = 'gg-yyy-M-d'): string
{
return CustomDate::getFormattedString($this, $format);
}
/**
* @param Era|null $era
* @param int|null $year
* @return Month[]
*/
public function getMonthsInYear(Era $era = null, int $year = null): array
{
$era ??= $this->era;
$year ??= $this->year;
return CustomDate::calcMonthsInYear($this->calendar, $year, $era);
}
/**
* @param Era|null $era
* @param int|null $year
* @param Month|null $month
* @return string[]
*/
public function getMonthArray(Era $era = null, int $year = null, Month $month = null): array
{
$year ??= $this->year;
$month ??= $this->month;
$era ??= $this->era;
$firstOfMonth = $this->getFirstOfMonth($era, $year, $month);
$lastOfMonth = $this->getLastOfMonth($era, $year, $month);
$daysInMonth = $month->day_count + ($firstOfMonth->sequence - 1) + ($this->calendar->days->count() - $lastOfMonth->sequence);
$result = [];
for ($i = 1; $i <= $daysInMonth; $i++) {
if ($i < $firstOfMonth->sequence || $i > $month->day_count) {
$result[] = '';
} else {
$result[] = $i - ($firstOfMonth->sequence - 1);
}
}
return $result;
}
/**
* @param Era|null $era
* @param int|null $year
* @param Month|null $month
* @return Day
*/
public function getFirstOfMonth(Era $era = null, int $year = null, Month $month = null): Day
{
$year ??= $this->year;
$month ??= $this->month;
$era ??= $this->era;
$daysInWeek = $this->calendar->days->count();
$dayNum = CustomDate::calcAbsoluteDayNum(
$this->calendar,
$year,
$month,
1,
$era);
$dayOfWeekNum = $dayNum % $daysInWeek;
if ($dayOfWeekNum === 0) $dayOfWeekNum = $daysInWeek;
return $this->calendar->days[$dayOfWeekNum - 1];
}
/**
* @param Era|null $era
* @param int|null $year
* @param Month|null $month
* @return Day
*/
public function getLastOfMonth(Era $era = null, int $year = null, Month $month = null): Day
{
$year ??= $this->year;
$month ??= $this->month;
$era ??= $this->era;
$daysInWeek = $this->calendar->days->count();
$dayNum = CustomDate::calcAbsoluteDayNum(
$this->calendar,
$year,
$month,
$month->day_count,
$era);
$dayOfWeekNum = $dayNum % $daysInWeek;
if ($dayOfWeekNum === 0) $dayOfWeekNum = $daysInWeek;
return $this->calendar->days[$dayOfWeekNum - 1];
}
/**
* @return Month[]
*/
public function getMonths(): array
{
return $this->calendar->months;
}
/**
* @return Day[]
*/
public function getDays(): array
{
return $this->calendar->days;
}
/**
* This returns a string representing a CustomDate object
* @param CustomDate $customDate
* @param string $format
* @return string
*/
private static function getFormattedString(CustomDate $customDate, string $format = 'gg-y-M-d'): string
{
$remainingFormatString = $format;
$result = '';
while (strlen($remainingFormatString) > 0) {
$currentChar = $remainingFormatString[0];
$numChar = strspn($remainingFormatString, $currentChar);
$result = match ($currentChar) {
'd' => match ($numChar) {
4 => $result . $customDate->day->name,
3 => $result . $customDate->day->abbreviation,
2 => $result . str_pad($customDate->dayNum, 2, '0', STR_PAD_LEFT),
1 => $result . $customDate->dayNum,
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 4 in a row."),
},
'f' => match ($numChar) {
3 => $result . round($customDate->millisecond, -2) / 100,
2 => $result . round($customDate->millisecond, -1) / 10,
1 => $result . $customDate->millisecond,
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 3 in a row."),
},
'F' => match ($numChar) {
3 => $result . preg_replace('/0+$/', '', round($customDate->millisecond, -2) / 100),
2 => $result . preg_replace('/0+$/', '', round($customDate->millisecond, -1) / 10),
1 => $result . preg_replace('/0+$/', '', $customDate->millisecond),
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 3 in a row.")
},
'g' => match ($numChar) {
3 => $result . $customDate->era->name,
2 => $result . $customDate->era->abbreviation,
1 => $result . $customDate->era->sequence,
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 3 in a row."),
},
'h' => match ($numChar) {
2 => $result . str_pad($customDate->hour == 0 ? 12 : ($customDate->hour > 12 ? $customDate->hour - 12 : $customDate->hour), 2, '0', STR_PAD_LEFT),
1 => $result . $customDate->hour == 0 ? 12 : ($customDate->hour > 12 ? $customDate->hour - 12 : $customDate->hour),
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row."),
},
'H' => match ($numChar) {
2 => $result . str_pad($customDate->hour, 2, '0', STR_PAD_LEFT),
1 => $result . $customDate->hour,
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row."),
},
'm' => match ($numChar) {
2 => $result . str_pad($customDate->minute, 2, '0', STR_PAD_LEFT),
1 => $result . $customDate->minute,
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row."),
},
'M' => match ($numChar) {
4 => $result . $customDate->month->name,
3 => $result . $customDate->month->abbreviation,
2 => $result . str_pad($customDate->month->sequence, 2, '0', STR_PAD_LEFT),
1 => $result . $customDate->month->sequence,
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 4 in a row."),
},
's' => match ($numChar) {
2 => $result . str_pad($customDate->second, 2, '0', STR_PAD_LEFT),
1 => $result . $customDate->second,
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row."),
},
't' => match ($numChar) {
2 => $result . $customDate->hour > 12 ? 'PM' : 'AM',
1 => $result . $customDate->hour > 12 ? 'P' : 'A',
default => throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row."),
},
'y' => match ($numChar) {
1 => $result . $customDate->year,
default => $result . str_pad($customDate->year, $numChar, '0', STR_PAD_LEFT)
},
default => $result . str_pad($currentChar, $numChar, $currentChar, STR_PAD_LEFT),
};
$remainingFormatString = substr($remainingFormatString, $numChar);
}
return $result;
}
/**
* This allows a string to set the date for a CustomDate object
* @param CustomDate $customDate
* @param string $dateTimeString
* @param string $format
* @return void
*/
private static function setFromFormattedString(CustomDate $customDate, string $dateTimeString, string $format = 'gg-y-M-d'): void
{
$controlChars = ['/', '-', ' ', ',', '.', ':', ';'];
$remainingFormatString = $format;
$remainingDateString = $dateTimeString;
$tempHr = -1;
$tempPeriod = ' ';
while (strlen($remainingFormatString) > 0) {
$currentChar = $remainingFormatString[0];
$numChar = strspn($remainingFormatString, $currentChar);
$segmentLn = strlen($remainingDateString);
foreach ($controlChars as $controlChar) {
$pos = strpos($remainingDateString, $controlChar);
if ($pos !== false) {
$segmentLn = min($segmentLn, $pos);
}
}
switch ($currentChar) {
case 'd':
switch ($numChar) {
case 4:
$found = false;
foreach ($customDate->calendar->days as $day) {
if (str_starts_with($remainingDateString, $day->name)) {
$found = true;
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
}
}
if ($found) break;
throw new InvalidArgumentException("Invalid date string, day name provided does not exist in calendar.");
case 3:
$found = false;
foreach ($customDate->calendar->days as $day) {
if (str_starts_with($remainingDateString, $day->abbreviation)) {
$found = true;
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
}
}
if ($found) break;
throw new InvalidArgumentException("Invalid date string, day abbreviation provided does not exist in calendar.");
case 2:
case 1:
$customDate->dayNum = (int)substr($remainingDateString, 0, $segmentLn);
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
default:
throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 4 in a row.");
}
break;
case 'f':
case 'F':
switch ($numChar) {
case 3:
case 2:
case 1:
$customDate->millisecond = (int)substr($remainingDateString, 0, $segmentLn);
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
default:
throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 3 in a row.");
}
break;
case 'g':
switch ($numChar) {
case 3:
$found = false;
foreach ($customDate->calendar->eras as $era) {
if (str_starts_with($remainingDateString, $era->name)) {
$customDate->era = $era;
$found = true;
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
}
}
if ($found) break;
throw new InvalidArgumentException("Invalid date string, era name provided does not exist in calendar.");
case 2:
$found = false;
foreach ($customDate->calendar->eras as $era) {
if (str_starts_with($remainingDateString, $era->abbreviation)) {
$customDate->era = $era;
$found = true;
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
}
}
if ($found) break;
throw new InvalidArgumentException("Invalid date string, era abbreviation provided does not exist in calendar.");
case 1:
$found = false;
foreach ($customDate->calendar->eras as $era) {
if ($era->sequence == (int)substr($remainingDateString, 0, $segmentLn)) {
$customDate->era = $era;
$found = true;
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
}
}
if ($found) break;
throw new InvalidArgumentException("Invalid date string, era number provided does not exist in calendar.");
default:
throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 3 in a row.");
}
break;
case 'h':
case 'H':
switch ($numChar) {
case 2:
case 1:
$tempHr = (int)substr($remainingDateString, 0, $segmentLn);
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
default:
throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row.");
}
break;
case 'm':
switch ($numChar) {
case 2:
case 1:
$customDate->minute = (int)substr($remainingDateString, 0, $segmentLn);
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
default:
throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row.");
}
break;
case 'M':
switch ($numChar) {
case 4:
$found = false;
foreach ($customDate->calendar->months as $month) {
if (str_starts_with($remainingDateString, $month->name)) {
$customDate->month = $month;
$found = true;
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
}
}
if ($found) break;
throw new InvalidArgumentException("Invalid date string, month name provided does not exist in calendar.");
case 3:
$found = false;
foreach ($customDate->calendar->months as $month) {
if (str_starts_with($remainingDateString, $month->abbreviation)) {
$customDate->month = $month;
$found = true;
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
}
}
if ($found) break;
throw new InvalidArgumentException("Invalid date string, month abbreviation provided does not exist in calendar.");
case 2:
case 1:
$found = false;
foreach ($customDate->calendar->months as $month) {
if ($month->sequence == (int)substr($remainingDateString, 0, $segmentLn)) {
$customDate->month = $month;
$found = true;
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
}
}
if ($found) break;
throw new InvalidArgumentException("Invalid date string, month number provided does not exist in calendar.");
default:
throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 4 in a row.");
}
break;
case 's':
switch ($numChar) {
case 2:
case 1:
$customDate->second = (int)substr($remainingDateString, 0, $segmentLn);
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
default:
throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row.");
}
break;
case 't':
switch ($numChar) {
case 2:
case 1:
$tempPeriod = $remainingDateString[0];
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
default:
throw new InvalidArgumentException("Invalid date string format, instances of '$currentChar' are limited to 2 in a row.");
}
break;
case 'y':
$customDate->year = (int)substr($remainingDateString, 0, $segmentLn);
$remainingDateString = substr($remainingDateString, $segmentLn);
break;
default:
$remainingDateString = substr($remainingDateString, 1);
break;
}
$remainingFormatString = substr($remainingFormatString, $numChar);
}
if ($tempHr >= 0 && $tempPeriod !== ' ') {
if (strtolower($tempPeriod) === 'p') {
$customDate->hour = ($tempHr + 12) % 24;
}
}
if(
empty($customDate->era)
|| empty($customDate->month)
|| $customDate->year < 1
|| $customDate->dayNum < 1
) {
throw new InvalidArgumentException("Can not set date, need to provide the calendar, era, month, year, and day number as a minimum.");
}
$customDate->day = CustomDate::calcDayOfWeek($customDate);
}
private static function calcDayOfWeek(CustomDate $customDate): Day
{
if(is_null($customDate->calendar)) {
throw new InvalidArgumentException("Calendar not set for date object provided.");
}
if(is_null($customDate->era)) {
throw new InvalidArgumentException("Era not set for date object provided.");
}
if(is_null($customDate->month)) {
throw new InvalidArgumentException("Month not set for date object provided.");
}
if($customDate->year < 1) {
throw new InvalidArgumentException("Year for date object provided must be greater than 0.");
}
if($customDate->dayNum < 1) {
throw new InvalidArgumentException("Day number for date object provided must be greater than 0.");
}
$absoluteDayNum = CustomDate::calcAbsoluteDayNum($customDate->calendar, $customDate->year, $customDate->month, $customDate->dayNum, $customDate->era);
$daysInWeek = $customDate->calendar->days->count();
$sequence = $absoluteDayNum % $daysInWeek;
if ($sequence === 0) $sequence = $daysInWeek;
return $customDate->calendar->days()->where('sequence', $sequence)->first();
}
/**
* @return Month[]
*/
private static function calcMonthsInYear(Calendar $calendar, int $year, Era $era = null): array
{
$result = [];
$absoluteYear = $year;
if ($era !== null) {
$absoluteYear = CustomDate::calcAbsoluteYear($calendar, $era, $year);
}
foreach ($calendar->months() as $month) {
if ($absoluteYear % $month->recurrence_period == 0) {
$result[] = $month;
}
}
usort($result, function ($a, $b) { return $a->sequence - $b->sequence; });
return $result;
}
private static function calcDaysInYear(Calendar $calendar, int $year, Era $era = null): int
{
$absoluteYear = $year;
if ($era !== null) {
$absoluteYear = CustomDate::calcAbsoluteYear($calendar, $era, $year);
}
$months = CustomDate::calcMonthsInYear($calendar, $absoluteYear);
$result = 0;
foreach ($months as $month) {
$result += $month->day_count;
}
return $result;
}
private static function calcAbsoluteYear(Calendar $calendar, Era $era, int $year): int
{
if ($era->sequence == 1)
return $year;
$result = 0;
foreach ($calendar->eras() as $e) {
if ($e->sequence < $era->sequence) {
$result += $e->duration;
}
}
return $result + $year;
}
private static function calcAbsoluteDayNum(Calendar $calendar, int $year, Month $month, int $dayNum, Era $era = null): int
{
$absoluteYear = $year;
if ($era !== null) {
$absoluteYear = CustomDate::calcAbsoluteYear($calendar, $era, $year);
}
$result = 0;
for ($i = 1; $i < $absoluteYear; $i++) {
$result += CustomDate::calcDaysInYear($calendar, $i);
}
$months = CustomDate::calcMonthsInYear($calendar, $absoluteYear);
foreach ($months as $mon) {
if ($mon->sequence < $month->sequence) {
$result += $mon->day_count;
}
}
$result += $dayNum;
return $result;
}
}
Mark Lewellyn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.