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

unable to get highcharts to redraw and reflow properly

I am currently working on creating a dynamic page that can display between 1-4 graphs. These graphs need to be able to resize when added or removed from the page. However, I have encountered a major issue with resizing the graphs after resizing the contain ...

Encountering an unforeseen issue with the config.kit.methodOverride while executing Svelte

While working on a Svelte project, I recently updated it to the latest version using the migration tools provided. However, now the project doesn't seem to interact with npm as expected. When I run npm i, it installs the node modules but throws an er ...

Invoking a nested method within Vue.js

I am facing an issue in my vuejs application with 2 methods. When I define method1 a certain way, it does not run as expected. method1: function(param1, param2){ // I can log param1 here thirdLib.debounce(function(param1, params2){ // It d ...

I am attempting to swap values within table cells using AngularJS. Would it be recommended to utilize ngBind or ngModel, or is there another approach that would

How can I make a table cell clickable in AngularJS to switch the contents from one cell to another, creating a basic chess game? I want to use angular.element to access the clicked elements and set the second clicked square equal to the first clicked using ...

What are some ways I can customize this jQuery :submit selector demonstration?

After reviewing the jQuery example provided here, I am curious about how to adjust the code in order to change the color of a cell only when the value of the submit button within that cell meets certain criteria. For instance: var submitEl = $( ...

Disabling Navigation with Arrow Keys in Prettyphoto

Is there a way to prevent arrow keys from functioning in PrettyPhoto for a specific instance? I have tried using keyboard_shortcuts:false, but it still reloads the frame if left or right arrow keys are pressed, causing the form inside to reset. However, co ...

Displaying a page using express.Router()

I'm having trouble figuring out how to incorporate EJS rendering into a file utilizing express.Router(). The usual method of router.set('view engine', 'ejs') doesn't seem applicable in this context. Any ideas on how I can succ ...

Encountering a 400 error when utilizing the Google Translate free API with Curl

I am attempting to utilize the free Google Translate API that is derived from Firefox's S3 Google Translator addon, by incorporating the following code: https://translate.google.com/translate_a/single?client=t&sl=auto& tl=en&hl=en&dt= ...

Retrieve a JSON file with Hebrew data from a server and then interpret it using Node.js

I have a JSON file with dynamic content stored on a remote server acting as an API. The file also includes Hebrew text in its values. How can I retrieve the response and convert it into a JSON object? Here is the code snippet I have put together using Re ...

The asterisk path is not processed by the Node command

Within my Test/Automation folder, I have multiple test cases such as a.js, b.js, c.js, and more. Currently, I am utilizing WebdriverJs Selenium to run these tests. To execute all the tests within the folder, I use the following command: node Test/**/*.js ...

Event handler for "copy" on the iPad

Is it possible to bind an event handler to the copy event on iPad or iPhone devices? ...

Finding the label that is linked to the current DIV or textarea by its "for" property

I am working on a project that involves two elements - a textarea and a div. Each element has a label attached to it using the "for" attribute in HTML. <textarea id="txta_1" class="txta" cols="40" rows="3" onkeyup ...

Tips for enabling or disabling elements within an array using React JS

I am looking to develop a feature where I can toggle individual boxes on and off by clicking on them. Currently, only one box at a time can be activated (displayed in green), but I want the ability to control each box independently without affecting the ot ...

Confused by the concept of Vuex

In my application, I am working with two resources: Projects and Pieces. Projects have multiple Pieces, and accessing a specific Piece is done through the following route: .../projects/:project_id/pieces/:piece_id Within Vuex, the currentProject is store ...

Using v-model in Vue 3 will result in modifications to the table class in Bootstrap 5

Below is a snippet of the code I wrote: <table class="table table-striped"> <tr class="table-dark"> <th>#</th> <th>Column 1</th> <th colspan="3">Column 2</th> </tr> <tr ...

Locate broken image links in Vue project

I have a Vue 3 project where all images are stored in public/assets/image and referenced in .vue files as assets/image/image.png. Occasionally, I may enter incorrect paths or update paths that are no longer valid. Is there an automated way to detect and ...

How to dynamically apply component-specific CSS in NextJS based on conditions

I'm working on my nextjs project and encountered an issue with adding conditional styling to a component. To address this, I created a component-level stylesheet called MyComponent.module.css, which includes the following styles: .primary { color: ...

Performing an AJAX request to validate a username when it loses

Hey everyone, I'm currently working on a script that checks the availability of a username in a MySQL database using an onblur event with AJAX. Here's the AJAX script: document.getElementById("r_username").onblur = function(){ var http ...

Upon reinstalling the node_modules in my Nuxt.js project, I encountered the error message "Must use import to load ES Module:~"

After reinstalling node_modules, I encountered an issue where ufo and node-fetch were missing. Upon adding them back in, running npm run dev resulted in an error when opening localhost in a browser. This same error persisted when cloning the project onto ...

What could be the reason for scope.$watch failing to function properly?

My AngularJS directive has a template with two tags - an input and an empty list. I am trying to watch the input value of the first input tag. However, the $watch() method only gets called once during initialization of the directive and any subsequent chan ...