Issue with Empty Date Time Format in Vue2 Date-Picker

In our company, we use vue2-datepicker to manage the starting and ending times of meetings. The dates are stored in "YYYY-MM-DD HH:mm" format on the backend, but we convert them to "DD-MM-YYYY HH:mm" format when retrieving the data in the mounted() hook. This conversion is necessary as it aligns with the date representation standards in our country.

Although I apply the same method to all datepickers, one particular instance presents an issue with the HH:mm format. To address this, I utilize a function called "responseDateTimeFormatter" to extract and convert the incoming YYYY-MM-DD HH:mm formatted date into the desired format.

When submitting the data, I employ the requestDateTimeFormatter function to convert it back to YYYY-MM-DD HH:mm for database storage. Despite following these steps, the <date-picker> components remain empty once the data has been converted.

Below are snippets of my code:

Date Picker:

              <date-picker ref="startDatepicker" id="startDate" name="startDate" v-model="meeting.startDate" :first-day-of-week="1" type="datetime" format="DD-MM-YYYY HH:mm" @change="startDateClick" :disabled-date="disableStartDate" :time-picker-options="timePickerOptions"></date-picker>

Upon conversion, the v-model appears as follows:

meetingStartDate = 30-07-2022 09:30

To achieve this conversion, I utilize the responseFormatter function below:

  responseTimeFormatter(dateTime) {
    var day = dateTime.slice(8, 10);
    var month = dateTime.slice(5, 7);
    var year = dateTime.slice(0, 4);
    var time = dateTime.slice(11, 16);

    return day + "-" + month + "-" + year + " " + time;
  },

Here is my block within the then() statement:

  .then((response) => {
    this.meeting = response
    console.log("MEETING", this.meeting)
    this.meeting.startDate = this.responseTimeFormatter(response.startDate)
    console.log("Start Date", this.meeting.startDate)
    
    this.meeting.endDate = this.responseTimeFormatter(response.endDate)
    console.log("End Date", this.meeting.endDate)
  })

Despite meeting.startDate being correctly formatted and aligned with the DatePicker's attribute, the component remains empty. This issue only arises when using HH:mm in datetime format. Any insights on how to resolve this would be greatly appreciated. Thank you in advance.

Answer №1

Upon exploring the vue2-datepicker package, I noticed that when a string date is passed as input, it displays an empty field indicating that it may not accept string types as dates and requires a date object instead.

In fact, there is no need for the responseTimeFormatter function. Simply pass your DateTime string to a Date object, and you're good to go :)

To implement this change, update your then block like so:

.then((response) => {
    this.meeting = response
 
    this.meeting.startDate = new Date(response.startDate)
    this.meeting.endDate = new Date(response.endDate)
  })

If you wish to convert the lengthy string generated by the Date object into a format suitable for your backend, consider using the following approach:

Add these two functions within your methods object:

 methods: {
    padTo2Digits(num) {
      return num.toString().padStart(2, "0");
    },
    formatDate(date) {
      return (
        [
          date.getFullYear(),
          this.padTo2Digits(date.getMonth() + 1),
          this.padTo2Digits(date.getDate()),
        ].join("-") +
        " " +
        [
          this.padTo2Digits(date.getHours()),
          this.padTo2Digits(date.getMinutes()),
          this.padTo2Digits(date.getSeconds()),
        ].join(":")
      );
    },
  },

When making an API call to send data to your backend, utilize the following snippet:

// Include relevant API call code here
this.formatDate(this.meeting.startDate)

For additional guidance, refer to:

Formatting a Date as YYYY-MM-DD hh:mm:ss in JavaScript

Understanding the Date Object in JavaScript

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

Is it possible to trigger a textbox text change event after autocompleting using jQuery

I recently implemented a jquery autocomplete plugin for a textbox: $('#TargetArea').autocomplete({ source: '@Url.Action("GetTarget", "Ads", new { type = "Zip", term = target })' }); The implementation is working as expected. ...

D3 circle packing showcases a concise two-line label text

I've browsed through the topics on this site, but none of the solutions provided worked for my issue. Is there a way to display text in two lines for long texts in D3 circle packing? The following code is what I am using to show labels on circles: c ...

Illumination scope for directional lights in three.js

In the world of three.js, calculating shadows for directional lights involves setting a range based on a bounding box that extends from the light source. This means that if I want to limit how far shadows are rendered, I need to adjust the bounding box geo ...

What could be causing the issue of not being able to access an element visible in AngularJS Videogular?

I am currently working on integrating the videogular-subtitle-plugin with the most recent version of Videogular/AngularJS. As a newcomer to AngularJS, I believe there must be a simple solution that I am overlooking. My main challenge lies within a directi ...

The strange behavior of !important, display:none, and .height()

While working with a piece of JS code yesterday, I stumbled upon something peculiar. There was a div element that was initially hidden using display:none, and I was utilizing its height in some JavaScript calculations. Everything was functioning properly u ...

Unable to utilize routes in Express.JS when integrated with nginx

After setting up nginx in front of Express.JS, everything seemed to be running smoothly. However, I encountered an issue when trying to access website.com/users, which resulted in a 404 Not Found error. It appears that accessing website.com works fine, but ...

Internet Explorer freezing when running selenium executeScript

Hey everyone, I've spent the past couple of days scouring the internet trying to find a solution to my modal dialog problem. There's a wealth of helpful information out there and everything works perfectly fine except for Internet Explorer. Speci ...

When a <a href> link is clicked, the Struts action should open as a popup

I have a form on my jsp page, <form action="test1_action" name="test" method="post" id="test"> Additionally, I have two distinct links: link1 and link2. When link1 is clicked, the form should be submitted with the action test1_action. $('#l ...

Set a variable in PHP by passing a value

In continuation of my previous post, I realized I missed a point and needed to start a new thread. Thankfully, I found a solution for the issue in my previous post and here is the final code: Scrapping code not working in php <?php $html = file_get_co ...

Issues with login validation in HTML when utilizing JSON and PHP

While creating a login form in HTML using JSON and PHP, I encountered an issue where the if statements in the success function were not working properly. However, the beforeSend and error functions are functioning as expected. Can someone assist me in iden ...

A React-based frontend solution designed exclusively for managing data structures and databases

Challenges with Product Management In my React App, the shop features products sourced solely from a JSON file as an external API, all managed on the frontend. Recently, I encountered a product with limited availability - only 20 pieces in stock. I am uns ...

Vue in Laravel triggers a 500 Internal Server Error with XHR when attempting to post data

Currently facing an issue with data storage in Laravel. I have followed the steps of creating a request using php artisan make:request, adding fillable fields to my Model, and incorporating the process into the Vue component. The button for form submissio ...

Triggering a JQuery slider event on each individual slider handle within the range

Can events be triggered based on the movement of individual slider handles? I am curious because I need to dynamically update a datepicker depending on which handle is moved. However, I'm unsure if there is a way to: Specify an event for a specifi ...

What is the best way to transfer variables in my specific scenario?

As I consider the optimal approach for managing my controllers, I find myself faced with a challenge of passing data between them. In my setup, I have multiple controllers that require sharing data throughout. For the first controller: app.controller(&a ...

Switch out text and calculate the frequency of letters in a given string

I have a string that looks like this: "061801850010300-09/A/B". My goal is to replace all "/" with "-" and also change "A" to "1" and "B" to "2". My objective is to assign each letter in the alphabet a numerical value - for example, A as 1, B as 2, C as 3 ...

Recognize when the DOM undergoes modifications

After taking Matt's suggestion, I have made changes to the .ready() call. In my workflow, I utilize jQuery to set up certain configurations like this: $(function () { $('.myThing').each(function() { ... configuring happens he ...

What is the best way to modify a CSS property using logical operators in JQuery?

If an element with the class ".has_padding" does not have any text content, it should be set to "display:none;". However, those elements with text inside should remain visible. Below is some code where I have styled the elements to demonstrate the issue. ...

The for loop does not pause for asynchronous code to complete

The for loop in my code has a function call that contains async code. However, the issue is that the for loop does not wait for the async code to return before continuing with the iterations. The function aFunctionThatRunsAsync is from a library that I ca ...

Enable hyperlink to open in a new browser tab after user clicks on button embedded inside an iFrame

<head> </head> <div> <iframe src="https://....."></iframe> </div> https://i.sstatic.net/dk21i.png I'm looking for a way to open the link in a new tab when clicking on this button. Currently, the page loads wi ...

Leveraging the power of fullpage.js to activate Velocity.js/Blast.js animations

Referencing a solution shared on this forum: Velocity.js/Blast.js starting opacity at 0 I am currently working with Velocity.js and Blast.js to implement a basic word-by-word loading animation, commonly used. This setup also involves Cycle2. Additionally, ...