Is there a way to retrieve the value from a moment-formatted date picker in the (YYYY-MM-DD) format?

I have a Vue application with a datepicker from Ant Design Vue that is returning the following moment object:

Moment {…}
_d: Thu Oct 24 1996 00:00:00 GMT+0800 (Malaysia Time)
_f: "YYYY-MM-DD"
_i: "1996-10-15"
_isAMomentObject: (...)
_isUTC: (...)
_isValid: (...)
_locale: (...)
_pf: (...)
__ob__: Observer {value: Moment, dep: Dep, vmCount: 0}
get _d: ƒ reactiveGetter()
set _d: ƒ reactiveSetter(newVal)
get _f: ƒ reactiveGetter()
set _f: ƒ reactiveSetter(newVal)
get _i: ƒ reactiveGetter()
set _i: ƒ reactiveSetter(newVal)
get _isAMomentObject: ƒ reactiveGetter()
set _isAMomentObject: ƒ reactiveSetter(newVal)
get _isUTC: ƒ reactiveGetter()
set _isUTC: ƒ reactiveSetter(newVal)
get _isValid: ƒ reactiveGetter()
set _isValid: ƒ reactiveSetter(newVal)
get _locale: ƒ reactiveGetter()
set _locale: ƒ reactiveSetter(newVal)
get _pf: ƒ reactiveGetter()
set _pf: ƒ reactiveSetter(newVal)
__proto__: Object

I need to extract the date in YYYY-MM-DD format.

When I retrieve the date directly from the onChange event using this code snippet, it works:

function(date = moment, dateString) {
      if (date) {
        console.log(dateString)
}

However, in my project, I'm using v-decorator to obtain all data from the form. Here's the script where I tried to get the date:

this.form.validateFields((error, values) => {
          console.log(values.birthday);
)}

This is the structure of my datepicker component:

<a-form-item v-bind="formItemLayout" label="Date Of Birth">
    <a-date-picker
     v-decorator="[ 'birthday',
      {
       initialValue: moment(profile.birthday),
        rules: [{required: true, message: 'Date Of Birth is required.'}]
      },
     ]"
       @change="handleAge"
       format="DD/MM/YYYY"
      style="width:120px;"
      />
     </a-form-item>

The above setup returns the moment object mentioned earlier. How can I receive only the date in YYYY-MM-DD format?

Answer №1

Did you give this a shot below?

When initial Rendering set initialValue to: moment(profile.birthday).format("YYYY-MM-DD")

<a-form-item v-bind="formItemLayout" label="Date Of Birth">
<a-date-picker
 v-decorator="[ 'birthday',
  {
    rules: [{required: true, message: 'Date Of Birth is required.'}],
    initialValue: moment(profile.birthday).format("YYYY-MM-DD"),
  },
 ]"
   @change="handleAge"
   format="DD/MM/YYYY"
  style="width:120px;"
  />
 </a-form-item>

When it's time for Submission:

this.form.validateFields((error, values) => {
     let birthday = moment(values.birthday).format("YYYY-MM-DD");

          console.log(birthday);
)}

Give it a test run and let me know if it does the trick or if you need further clarification.

Answer №2

When using ant-design, the Datepicker component defaults to returning a moment object as the value. To extract only the Date value from the moment object, some logic needs to be implemented. You can achieve this by formatting the date in YYYY-MM-DD format.

Here is an example of creating a function to convert the moment object into the desired format:

const convert = (str) => {
    var date = new Date(str),
    mnth = ("0" + (date.getMonth() + 1)).slice(-2),
    day = ("0" + date.getDate()).slice(-2);
    return [date.getFullYear(), mnth, day].join("-");
  };
this.form.validateFields((error, values) => {
    console.log(convert(values.birthday));
)}

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

Commencing CSS Animation Post Full Page Loading

I am looking for a solution using WordPress. In my specific case, I want the CSS Animations to take effect only after the page has completely loaded. For example: click here This is my HTML: <div class="svg-one"> <svg xmlns="ht ...

Constructing hierarchical objects in JavaScript

I am looking to create a complex nested object in JavaScript that follows a specific structure. const data = { name: 'Context 1', children: [ { name: 'Option 1', children: [ { name: 'Context&ap ...

React - passing down a ref as a prop isn't functioning as expected

In my current project, I am utilizing the react-mui library and aiming to incorporate a MenuList component from the MenuList composition available here. An issue arises when passing a ref as a prop down to a child component containing a menu. For reference ...

Experiencing difficulties while utilizing the event bus for transmitting data?

Need help with sharing data between two components? Here's the code for the first component: <template> <div class="row"> <label id="chatRoom">{{chatRoom}} <input type="text" id="chatInput" v-model="chatRoomVal"></la ...

Implementing Material UI Slider component to update state upon mouse release, enabling real-time sliding functionality

Is there a way to update the new state only upon mouse release for a Material UI slider, while still allowing real-time tracking of the slide? Material UI offers two events: onChange and onChangeCommitted. The latter gives the desired end result, but the s ...

How can I get rid of the excessive white space in my Vue.js/Vuetify dialog box?

I am facing an issue with my web app's dialog box where there is empty white space appearing between the v-cards and the v-card-action buttons (Save and Cancel). Is there a way to remove this whitespace or scrollbar? I attempted to place the Cancel/S ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...

What is causing the qtip tooltip to show up on buttons with different ids?

I have a requirement to display tooltips only for specific buttons and not for others. I am facing an issue where the tooltip intended for the TAB button is showing up when hovering over other buttons like FOO and BAR as well. Could this be due to them sha ...

Is HTML-escaping necessary when implementing regex checks?

As I develop a web application that takes user input through HTML inputs and forwards it to my tomcat server for processing, my current workflow is as follows: Client JS -> collect HTML input -> perform regex validation -> if successful -> send data via ...

What is the best way to target specific text within the DOM without including text within attributes?

We are currently displaying search results from various posts on our website, and we would like to highlight the search terms in the displayed content. Currently, we are implementing this functionality on the backend using PHP. We iterate through the post ...

Cannot iterate over array using v-for - The property or method "dailyData" is not defined in the instance but referenced during rendering

I need help with displaying daily weather data in a table <tr :v-for="dailyData in weatherData.daily"> <td>{{ dailyData }}</td> </tr> The weatherData variable is a data property that contains the necessary information. ...

Save the result of a terminal command into an sqlite database

When I run a particular shell command in node js, the output is displayed on the console. Is there a method to store this output in a variable so that it can be POSTed to an Sqlite database? const shell = require('shelljs'); shell.exec('a ...

Dealing with Javascript exceptions and sending email notifications in Django

I appreciate the traditional method of handling server-side exceptions in Django using Python. I am interested in finding a similar approach for client-side exception handling in JavaScript. So far, I have come across only one option which is DamnIT, but ...

Content displayed in the center of a modal

Struggling to center the captcha when clicking the submit button. Check out the provided jsfiddle for more details. https://jsfiddle.net/rzant4kb/ <script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class=" ...

Discovering the oldest date in an array with JavaScript

Is there a way to identify the earliest date, also known as the minimum date, within an array using JavaScript? For instance: ["10-Jan-2013", "12-Dec-2013", "1-Sep-2013", "15-Sep-2013"] The desired output would be: ...

Moving various divisions through Javascript by clicking various buttons although sharing the same identifier

I am working with the script below: $(document).ready(function() { $('.expandButton').click(function() { $('.expandableSection').toggle("slide"); }); }); My goal is to apply this script to multiple sections. However, ...

Splitting a td tag into multiple columns dynamically with Angular

I am attempting to dynamically split the table element into separate columns. My desired layout should resemble this: The values for name and surname are fixed at 1, but the values for subjects and grades can vary (there may be 2 or more columns). Below ...

Sending product identification to content_ids for Facebook Pixel tracking

Looking to implement Facebook Pixel for tracking the ViewContent event on product pages. According to Facebook, it's necessary to provide content_ids or contents along with a content_type. I assume that the content_type should always be 'product ...

Using words instead of symbols to represent logical operators

When coding in C++, I typically prefer using the 'word' operators: not instead of ! and instead of && or instead of || I find it easier to read, especially when negating statements with not. Is there a similar approach possible in ...

Despite having unique ids, two file input forms are displayed in the same div in the image preview

Running into a minor issue once again. It may not be the most eloquent query, but I'm genuinely stuck and in need of some assistance. I am attempting to showcase image previews of selected files in a file input form. I have a jQuery script that reads ...