Leverage moment.js for formatting dates within a Vue component

I am currently working on a Vue component that includes an input field with a date type:

<input
    type="date"
    name="start_date"
    id="start_date"
    v-model="absence.start_date"
>

Within my script, I am attempting to format the date for proper display:

<script>
    export default {
        data() {
            return {
                absence: {
                    start_date: null,
                }
            }
        },
        created() {
            const request = axios
                .get(`/api/absences/${this.$route.params.id}`)
                .then(response => {
                    this.absence = response.data.data;
                });
        }
    }
</script>

Unfortunately, the format from the API response is causing issues.

When I manually set the date, it works with this format:

start_date: '2021-01-01',

However, it gets overridden by the data from the API call. I have Moment.js installed in app.js, how can I utilize it to format the date from the API response?

EDIT

This is the API response:

{"success":true,"data":{"id":1,"start_date":"2021-07-24 00:00:00","end_date":"2021-07-25 00:00:00","notes":"Quis nisi repellendus ipsa. Eum asperiores sunt iusto exercitationem autem. Qui harum adipisci praesentium laboriosam. Fugit quasi voluptatem excepturi et non autem atque quibusdam. Sed aperiam molestias quaerat incidunt.","created_at":"2021-06-28T19:34:16.000000Z","updated_at":"2021-07-03T15:46:10.000000Z","status":1}}

Answer №1

If you want to achieve a similar result, you can use the following code snippet as a guide. View a working example here

Remember to ensure that you have installed Moment.js before proceeding

<input
   type="date"
   name="start_date"
   id="start_date"
   v-model="formattedStartDate"
>

// Ensure that Moment.js is properly installed

<script>
    import moment from 'moment'

    export default {
        data() {
            return {
                absence: {
                    start_date: null,
                }
            }
        },
        computed: {
            formattedStartDate() {
                return moment(this.absence.start_date).format('yyyy-MM-DD');
            }
        },
        created() {
            const request = axios
                .get(`/api/absences/${this.$route.params.id}`)
                .then(response => {
                    this.absence = response.data.data;
                });
        }
    }
</script>

Answer №2

When using the

<input type="date">
element, it is important to note that only the date portion of an ISO date string is considered a valid value, even if the API data contains both date and time information:

{
  "start_time": "2021-07-24 00:00:00"
                            ^^^^^^^^
}

To extract the date from a string like this, you can easily use the String.prototype.split method on the space character, and then take the first element of the resulting array (which is the date):

const data = response.data.data
this.absence = {
  ...data,
  start_date: data.start_date.split(' ')[0]
}

Check out the demo for a practical example.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can Mbox content be loaded dynamically according to the selected option in a dropdown menu, instead of loading it when

I am looking to enhance my asp.net page by adding a new MBox that will be triggered based on the dropdown selected value. Unlike other MBoxes on the page that load on page load, I want this new MBox to dynamically pass custom parameters to T&T when a val ...

Alter a data value using a method that is invoked during the mounted lifecycle hook

In the following code, the objective is to update a data variable called sticky to true if the scroll position is greater than 0. export default { components: { }, data() { return { menuVisible: false, sticky: false, } }, mou ...

Unable to retrieve accurate information

I am currently in the process of developing an application that utilizes Spring Boot and ReactJS. I encounter an issue where, despite entering correct data values in the form on the client side using the POST method, the response displays NULL values. Upo ...

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...

Unable to open Google Maps link within React application

I've set up a conditional link based on location, using the following code: <a href={`https://maps.google.com/maps?q=${delivery_branch.latitude},${delivery_branch.longitude}`} target={"_blank"} >{`${delivery_branch.street}, ${d ...

"Centered in the middle of the screen, an animated

Encountering an issue with this code on Chrome. Clicking on the checkbox causes the text/checkbox to shift in position/padding/margin unexpectedly.. :( View the code on JSFiddle HTML <input id="inp" type="checkbox" /> <div id="cb" class="inp_ch ...

Is it possible to make the v-toolbar-title fixed within a v-navigation-drawer using Vuetify?

Can the <v-toolbar-title> be fixed within a <v-navigation-drawer>? <v-card class="d-inline-block elevation-12"> <v-navigation-drawer hide-overlay permanent stateless height="440" value="true"> <v-toolbar color="whi ...

Can you eliminate the commas and turn it into a string?

function EncryptMessage(message) { var encryptedArr = []; for(i=0;i<message.length+1;i++){ var unicode = message.charCodeAt(i); var encryptedUnicode; var newCharacter = String.fromCharCode(encryptedUnicode); if( ...

Steps for checking if the specified row has been accurately filled out in a loop

Here is an example of how my JSON data is structured: { "main_object": { "id": "5", "getExerciseTitle": "TestFor", "language": "nl_NL", "application": "lettergrepen", "main_object": { "title": "TestFor", "language": "nl_NL", "exercises": [ { ...

Utilizing $store in field callback with VueJS and vue-form-generator

I've been utilizing the vue-form-generator component to work on my project. My goal is to update a variable in the store using the response from a callback function. Below is what I think is the relevant code (found inside the schema:fields property): ...

Tips for dynamically appending a string to a predefined variable in React

When I was working on creating a text input space using the input type area and utilizing the onChange utility, everything was running smoothly. Now, my task is to incorporate an emoji bar and insert a specific emoji into the input space upon clicking it. ...

jQuery does not support animations for sliding up or down

I'm struggling to conceal a navigation element once the top of the #preFooter section is scrolled to. In order to make the nav element mobile-friendly, I have designed both the .tab-wrap and .tab-wrap-mobile. To enable these elements to slide away w ...

JavaScript hovering drop-down feature

Hi there, I'm just starting out with javascript and could use some help with a simple script. I have a shopping cart drop down that currently activates when clicked. However, I want it to fade in when hovered over instead. I've tried using .hove ...

Having difficulty uploading an image to Facebook through the graph API

I have a requirement to upload a photo to Facebook using the Javascript SDK, but I am experiencing some difficulties: Firstly, FB.login(function (response) { if (response.authResponse) { va ...

Storing the results of an Ajax call in a global variable

What is the best way to store and access the output of an ajax call within a global variable? let globalOutput = []; $.ajax({ type: "GET", url: uri, dataType : "json", contentType: "application/json", data: { input: filterVa ...

What is the best way to generate conditional test scenarios with Protractor for testing?

Currently, there are certain test cases that I need to run only under specific conditions. it ('user can successfully log in', function() { if(siteAllowsLogin) { ..... } The problem with the above approach is that even when sitesNo ...

How can Vue.Draggable's draggable functionality be toggled on and off?

I'm faced with a situation where the elements being wrapped should only be draggable under specific conditions. I managed to handle it in my HTML code like this: <draggable v-if='somePassingConditions'> <my-component></my-comp ...

Using jQuery to implement tiered radio buttons styled with Bootstrap

I am currently in the process of learning jQuery, so please excuse my lack of knowledge in this area. I am working on a web form using Bootstrap that involves tiered radio buttons. When the user selects "Yes" for the first option, it should display the ne ...

Live streaming updates directly from Firebase

In order to achieve real-time updates from Firebase, my objective is to retrieve comments from Firebase and display them on this.note. I seem to have made a mistake in the update() function. Here is the tutorial I followed: link. methods: { update(){ db.c ...