Vue DateTime Component with Bootstrap

·

0 min read

Unfortunately Firefox does not yet support the datetime-local input field. Since I am avid Firefox user, I created a Vue Component which helps with DateTime fields.

Imagine you have a Timestamp in your database with the format Y-m-d H:i:s, e.g. "2019-06-05 10:20:00"

<template>
<div class="form-group row">
    <label class="col-sm-2 col-form-label text-right">{{ leftLabel }}</label>
    <div class="col-sm-10">
        <div class="row">
            <div class="col-sm-5">
                <input :class="(errors.length > 0) ? 'is-invalid form-control' : 'form-control'" type="date" v-model="date" @input="updateValue">
            </div>
            <div class="col-sm-5">
                <input class="form-control" type="time" v-model="time" @input="updateValue">
            </div>
        </div>
        <!-- Use the Slot to add custom descriptions or error messages -->
        <slot></slot>
    </div>
</div>
</template>

<script>
export default {
    name: "DateTime",
    props: {
        value: String,
        leftLabel: String,
        errors: {
            type: Array,
            default: () => [],
        }
    },
    data() {
        return {
            date: this.value ? this.value.split(' ').shift() : '',
            time: this.value ? this.value.split(' ').pop().substr(0, 5) : ''
        }
    },
    methods: {
        updateValue() {
            // Reconstruct to the valid timestamp format
            this.$emit('input', this.date + " " + this.time + ":00");
        }
    }
}
</script>

This Component splits the timestamp into date and time fields (which Firefox supports) and reconstructs the timestamp back into one value if the users changed the values.

If you save this as "DateTime.vue" Component you can use it inside your forms like:

<date-time left-label="Your Datetime" v-model="form.started_at">
    <div class="text-danger" v-if="$page.errors.started_at">
        {{ $page.errors.started_at[0] }}
    </div>
</date-time>

If you wondering about the $page part, its because I started using Inertia

Your timestamp will be updated accordingly.