如何以 (YYYY-MM-DD) 格式获取 moment.js 日期选择器的值?

3

我有一个使用Ant Design Vue的日期选择器的Vue应用程序,返回

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

我需要的日期格式是YYYY-MM-DD

使用以下代码从onChange事件中直接获取会成功。

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

但在我的项目中,我正在使用v-decorator通过表单获取所有数据。 这是我的脚本,我尝试调用日期:

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

这是我的日期选择器结构:

<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>

并且它返回了上述时刻。我怎样才能只获取YYYY-MM-DD格式?


我不明白你从哪里获取数据以及你使用的方法是什么。 - EthanZone Coding
请尝试使用格式为'YYYY-MM-DD'。参考:https://momentjs.com/docs/ - Danielprabhakaran N
2个回答

1

您尝试过以下方法吗?

用于初始渲染: initialValue: 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>

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

          console.log(birthday);
)}

如果这对您有用,或者您需要更多的解释,请告诉我。


0
在 ant-design 中,Datepicker 默认返回 moment 对象作为值,因此我使用了一些逻辑来仅返回 moment 对象中的日期值。这是如何以 YYYY-MM-DD 格式返回日期的方法。
创建一个函数来更改 moment 对象,以返回 YYYY-MM-DD 格式的日期。
以下是在您的项目中执行此操作的方法:
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));
)}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接