Added custom date format

This commit is contained in:
2026-07-18 00:47:14 +10:00
parent 792cb082fd
commit 39c0ce1b44
7 changed files with 112 additions and 212 deletions
+1 -1
View File
@@ -28,7 +28,7 @@ enum FlightNotificationType: string
{
return match ($this) {
self::Booked => "{$user->name} booked a new flight",
self::Logged => "{$user->name} logged a new flight",
self::Logged => "{$user->name} logged a historic flight",
self::Cancelled => "{$user->name} cancelled a flight",
self::Departed => "{$user->name} is taking off!",
self::Arrived => "{$user->name} has landed!",
+20 -1
View File
@@ -153,7 +153,26 @@ class User extends Authenticatable implements MustVerifyEmail
->toJson();
});
$collection = collect(json_decode($json));
$dateFormat = auth()->user()?->resolved_settings['date_format'] ?? 'j M Y';
$timeFormat = auth()->user()?->resolved_settings['time_format'] === '24hr' ? 'Hi' : 'g:iA';
$collection = collect(json_decode($json))
->map(function ($flight) use ($dateFormat, $timeFormat) {
$departure = Carbon::parse($flight->departure_date)
->setTimezone($flight->departure_airport->timezone);
$arrival = Carbon::parse($flight->arrival_date)
->setTimezone($flight->arrival_airport->timezone);
$flight->departure_date_display = $departure->format($dateFormat);
$flight->departure_time_display = $departure->format($timeFormat);
$flight->arrival_date_display = $arrival->format($dateFormat);
$flight->arrival_time_display = $arrival->format($timeFormat);
return $flight;
});
$today = now('UTC')->toDateString();
return match ($filter) {
+13
View File
@@ -54,6 +54,19 @@ class SettingsRegistry
['value' => '24hr', 'label' => '24-Hour'],
],
],
[
'key' => 'date_format',
'type' => 'select',
'label' => 'Date Format',
'category' => 'Localization',
'default' => 'j M Y',
'options' => [
['value' => 'j M Y', 'label' => '20 Feb 2015'],
['value' => 'Y-m-d', 'label' => '2015-02-20'],
['value' => 'd/m/Y', 'label' => '20/02/2015'],
['value' => 'm/d/Y', 'label' => '02/20/2015'],
],
],
[
'key' => 'default_login_page',
'type' => 'select',
@@ -12,7 +12,6 @@ import { usePage } from "@inertiajs/vue3";
import { User } from "@/Types/types";
import Mono from "@/Components/FlightsGoneBy/Mono.vue";
import DayDifference from "@/Components/FlightsGoneBy/DayDifference.vue";
import Time from "@/Components/FlightsGoneBy/Time.vue";
const props = defineProps<{
flight: Flight
@@ -99,12 +98,12 @@ const showColumn = (column: string) => props.columnsToShow.includes(column)
<td v-if="showColumn('departure_time')" class="v-data-table__td">
<span class="time-cell">
<Mono small><Time :value="flight.departure_time_display" /></Mono>
<Mono small>{{flight.departure_time_display}}</Mono>
</span>
</td>
<td v-if="showColumn('arrival_time')" class="v-data-table__td arrival-time-cell">
<Mono small><Time :value="flight.arrival_time_display" /></Mono>
<Mono small>{{flight.arrival_time_display}}</Mono>
<DayDifference :value="flight.arrival_day_difference" />
</td>
@@ -1,42 +0,0 @@
<script setup lang="ts">
import {computed} from "vue";
import {usePage} from "@inertiajs/vue3";
import {SharedProps} from "@/Types/types";
const props = defineProps<{
value: string; //Time in g:iA format
}>()
const page = usePage<SharedProps>().props;
const timeFormatString = page.auth.user?.resolved_settings?.time_format
const formattedTime = computed(() => {
if (timeFormatString !== "24hr") {
return props.value;
}
const match = props.value.match(/^(\d{1,2}):(\d{2})(AM|PM)$/i);
if (!match) {
return props.value;
}
let [, hourStr, minuteStr, meridiem] = match;
let hour = parseInt(hourStr, 10);
if (meridiem.toUpperCase() === "PM" && hour !== 12) {
hour += 12;
} else if (meridiem.toUpperCase() === "AM" && hour === 12) {
hour = 0;
}
return `${hour.toString().padStart(2, "0")}${minuteStr}`;
});
</script>
<template>
<span>{{ formattedTime }}</span>
</template>
<style scoped>
</style>
+76 -164
View File
@@ -41,95 +41,9 @@ const isEdit = !!props.flight
// ── User format preferences ─────────────────────────────────────────────────
const timeFormat = computed(() => page.auth?.user?.resolved_settings?.time_format ?? 'ampm')
// day.js/date-fns-style tokens, e.g. 'D MMM YYYY' -> "7 Dec 2026". Not user-configurable yet.
const dateFormat = computed(() => 'DD-MM-YYYY')
// ── Date token formatting/parsing helpers (D, DD, M, MM, MMM, MMMM, YY, YYYY) ──
const pad = (n: number) => String(n).padStart(2, '0')
const MONTHS_SHORT = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
const MONTHS_LONG = ['January','February','March','April','May','June','July','August','September','October','November','December']
// Formats a Date according to a token format string. Tokens matched longest-first
// so e.g. "YYYY" isn't partially consumed by a lone "Y"-style rule.
function formatDateForFormat(d: Date | null, format: string): string {
if (!d) return ''
return format.replace(/YYYY|YY|MMMM|MMM|MM|M|DD|D/g, (token) => {
switch (token) {
case 'YYYY': return String(d.getFullYear())
case 'YY': return String(d.getFullYear()).slice(-2)
case 'MMMM': return MONTHS_LONG[d.getMonth()]
case 'MMM': return MONTHS_SHORT[d.getMonth()]
case 'MM': return pad(d.getMonth() + 1)
case 'M': return String(d.getMonth() + 1)
case 'DD': return pad(d.getDate())
case 'D': return String(d.getDate())
default: return token
}
})
}
// Extracts the ordered list of D/M/Y tokens from a format string, e.g.
// "D MMM YYYY" -> ['D', 'MMM', 'YYYY']
function getFormatTokens(format: string): string[] {
return format.match(/YYYY|YY|MMMM|MMM|MM|M|DD|D/g) ?? ['D', 'MMM', 'YYYY']
}
// Parses user-typed text into a Date, following the token order of `format`.
// Splits on any run of non-alphanumeric characters, so "/", "-", ".", and
// spaces are all accepted as separators regardless of what the format uses.
// Month tokens (MMM/MMMM) match against month names case-insensitively.
function parseDateInputStr(input: string, format: string): Date | null {
const trimmed = input.trim()
if (!trimmed) return null
const parts = trimmed.split(/[^a-zA-Z0-9]+/).filter(Boolean)
const tokens = getFormatTokens(format)
if (parts.length !== tokens.length) return null
let day: number | null = null
let month: number | null = null // 0-indexed
let year: number | null = null
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i]
const part = parts[i]
if (token === 'D' || token === 'DD') {
const val = parseInt(part, 10)
if (isNaN(val)) return null
day = val
} else if (token === 'M' || token === 'MM') {
const val = parseInt(part, 10)
if (isNaN(val)) return null
month = val - 1
} else if (token === 'MMM' || token === 'MMMM') {
const lower = part.toLowerCase()
const idx = MONTHS_LONG.findIndex(m => m.toLowerCase().startsWith(lower) || lower.startsWith(m.slice(0, 3).toLowerCase()))
if (idx === -1) return null
month = idx
} else if (token === 'YYYY') {
const val = parseInt(part, 10)
if (isNaN(val)) return null
year = val
} else if (token === 'YY') {
const val = parseInt(part, 10)
if (isNaN(val)) return null
year = val < 100 ? 2000 + val : val
}
}
if (day === null || month === null || year === null) return null
const date = new Date(year, month, day)
// Reject dates that overflowed (e.g. day 31 in a 30-day month)
if (date.getFullYear() !== year || date.getMonth() !== month || date.getDate() !== day) {
return null
}
return date
}
// ── Flight number lookup ──────────────────────────────────────────────────────
const flightNumber = ref(props.flight?.flight_number ?? '')
@@ -397,47 +311,36 @@ const arrivalMax = computed(() => getArrivalBound(form, 3))
const arrivalMinDate = computed(() => arrivalMin.value ? new Date(arrivalMin.value) : undefined)
const arrivalMaxDate = computed(() => arrivalMax.value ? new Date(arrivalMax.value) : undefined)
// ── Editable, format-aware date text inputs ─────────────────────────────────
// ── Native date inputs ───────────────────────────────────────────────────────
// departureDatePart / arrivalDatePart stay the source of truth as Date
// objects. These input refs are what the text-fields actually bind to, so
// the user can type freely; parsing only commits on blur/enter.
// objects. These computed get/set pairs are what the native <input type=date>
// elements bind to — the browser handles locale display, typing, and
// validation itself, so no custom format-aware parsing is needed here.
// The Vuetify v-date-picker is still available via a separate calendar icon
// for users who prefer to pick from a calendar rather than type.
const departureDateInput = ref(formatDateForFormat(departureDatePart.value, dateFormat.value))
const arrivalDateInput = ref(formatDateForFormat(arrivalDatePart.value, dateFormat.value))
watch([departureDatePart, dateFormat], () => {
departureDateInput.value = formatDateForFormat(departureDatePart.value, dateFormat.value)
})
watch([arrivalDatePart, dateFormat], () => {
arrivalDateInput.value = formatDateForFormat(arrivalDatePart.value, dateFormat.value)
})
function commitDepartureDateInput() {
if (!departureDateInput.value.trim()) {
departureDatePart.value = null
return
}
const parsed = parseDateInputStr(departureDateInput.value, dateFormat.value)
if (parsed) {
departureDatePart.value = parsed
} else {
departureDateInput.value = formatDateForFormat(departureDatePart.value, dateFormat.value)
}
function toIsoDateString(d: Date | null): string {
if (!d) return ''
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
}
function commitArrivalDateInput() {
if (!arrivalDateInput.value.trim()) {
arrivalDatePart.value = null
return
}
const parsed = parseDateInputStr(arrivalDateInput.value, dateFormat.value)
if (parsed) {
arrivalDatePart.value = parsed
} else {
arrivalDateInput.value = formatDateForFormat(arrivalDatePart.value, dateFormat.value)
}
function fromIsoDateString(value: string): Date | null {
if (!value) return null
const [y, m, d] = value.split('-').map(Number)
if (!y || !m || !d) return null
return new Date(y, m - 1, d)
}
const departureDateValue = computed({
get: () => toIsoDateString(departureDatePart.value),
set: (value: string) => { departureDatePart.value = fromIsoDateString(value) },
})
const arrivalDateValue = computed({
get: () => toIsoDateString(arrivalDatePart.value),
set: (value: string) => { arrivalDatePart.value = fromIsoDateString(value) },
})
// ── Editable, format-aware time text fields ────────────────────────────────
// departureTimePart / arrivalTimePart stay the source of truth as internal
// "HH:mm" (24hr) strings. These input refs are what the text-fields actually
@@ -569,28 +472,30 @@ function commitArrivalTimeInput() {
<!-- Departure date + time -->
<v-row>
<v-col cols="12" sm="6">
<v-menu v-model="depDateMenu" :close-on-content-click="false">
<template #activator="{ props: menuProps }">
<v-text-field
v-bind="menuProps"
v-model="departureDateInput"
label="Departure Date"
clearable
prepend-inner-icon="mdi-calendar"
:placeholder="dateFormat"
:disabled="!lookupComplete"
:error-messages="submitForm.errors.departure_date"
@click:clear="clearDepartureDate"
@blur="commitDepartureDateInput"
@keydown.enter="commitDepartureDateInput"
autocomplete="false"
/>
<v-text-field
v-model="departureDateValue"
type="date"
label="Departure Date"
prepend-inner-icon="mdi-calendar"
:disabled="!lookupComplete"
:error-messages="submitForm.errors.departure_date"
>
<template #append-inner>
<v-menu v-model="depDateMenu" :close-on-content-click="false">
<template #activator="{ props: menuProps }">
<v-icon
v-bind="menuProps"
icon="mdi-calendar-month"
style="cursor: pointer"
/>
</template>
<v-date-picker
v-model="departureDatePart"
@update:model-value="depDateMenu = false"
/>
</v-menu>
</template>
<v-date-picker
v-model="departureDatePart"
@update:model-value="depDateMenu = false"
/>
</v-menu>
</v-text-field>
</v-col>
<v-col cols="12" sm="6">
<v-menu v-model="depTimeMenu" :close-on-content-click="false">
@@ -626,29 +531,32 @@ function commitArrivalTimeInput() {
<!-- Arrival date + time -->
<v-row>
<v-col cols="12" sm="6">
<v-menu v-model="arrDateMenu" :close-on-content-click="false">
<template #activator="{ props: menuProps }">
<v-text-field
v-bind="menuProps"
v-model="arrivalDateInput"
label="Arrival Date"
clearable
prepend-inner-icon="mdi-calendar"
:placeholder="dateFormat"
:disabled="!lookupComplete"
:error-messages="submitForm.errors.arrival_date"
@click:clear="clearArrivalDate"
@blur="commitArrivalDateInput"
@keydown.enter="commitArrivalDateInput"
/>
<v-text-field
v-model="arrivalDateValue"
type="date"
label="Arrival Date"
prepend-inner-icon="mdi-calendar"
:disabled="!lookupComplete"
:error-messages="submitForm.errors.arrival_date"
>
<template #append-inner>
<v-menu v-model="arrDateMenu" :close-on-content-click="false">
<template #activator="{ props: menuProps }">
<v-icon
v-bind="menuProps"
icon="mdi-calendar-month"
style="cursor: pointer"
/>
</template>
<v-date-picker
v-model="arrivalDatePart"
:min="arrivalMinDate"
:max="arrivalMaxDate"
@update:model-value="arrDateMenu = false"
/>
</v-menu>
</template>
<v-date-picker
v-model="arrivalDatePart"
:min="arrivalMinDate"
:max="arrivalMaxDate"
@update:model-value="arrDateMenu = false"
/>
</v-menu>
</v-text-field>
</v-col>
<v-col cols="12" sm="6">
<v-menu v-model="arrTimeMenu" :close-on-content-click="false">
@@ -860,4 +768,8 @@ function commitArrivalTimeInput() {
</template>
<style scoped>
:deep(input[type="date"]::-webkit-calendar-picker-indicator) {
display: none;
-webkit-appearance: none;
}
</style>
-1
View File
@@ -191,7 +191,6 @@ watch(() => form.flight_reason, (val) => console.log('flight_reason changed:', v
<v-select v-model="form.seat_type" label="Seat Type" :items="flight.seat_types" :error-messages="submitForm.errors.seat_type_id" />
</v-col>
<v-col cols="12" md="6">
{{console.log(form.flight_reason)}}
<v-select v-model="form.flight_reason" label="Reason" :items="flight.flight_reasons" :error-messages="submitForm.errors.flight_reason_id" />
</v-col>
</v-row>