【问题标题】:Changing date format using moment使用时刻更改日期格式
【发布时间】:2021-03-03 09:24:59
【问题描述】:

我正在使用具有 moment.js 的日期选择器,目前我得到的日期格式是 MM/DD/YYYY。我想将此格式更改为 DD/MM/YYYY。我该怎么做?

这就是我调用日期选择器组件的方式。

<DatePickerComponent
    datePickerClass={"form-control quick-checkout-input-filed" +   (this.state.errorFields.dob ? " error-field" : "")}
    datePickerId="dob"
    datePickerName="dob"
    datePickerMaxDate={moment(new Date()).format('YYYY-MM-DD')}
    datePickerChangeAction={this.onChangeAction}
    datePickerBlurAction={this.onBlurAction}
    datePickerPlaceholder="Select Date"
/>

我还附上了日期选择器的屏幕截图。

这是我的组件。

import React, { PureComponent } from 'react';

// sample DatePickerComponent calling way

class DatePickerComponent extends PureComponent{
    constructor(props){
        super(props);
        this.clickFieldHandler=this.clickFieldHandler.bind(this);
        this.onBlurFieldHandler=this.onBlurFieldHandler.bind(this);
        this.state={fieldType: "text"};
    }
    render(){
        return(
            <div key="name_1">
                <input
                    onFocus={ this.clickFieldHandler }
                    placeholder={ this.props.datePickerPlaceholder }
                    type={ this.state.fieldType }
                    className={ this.props.datePickerClass }
                    id={ this.props.datePickerId }
                    name={ this.props.datePickerName }
                    defaultValue={ this.props.datePickerValue }
                    min={ this.props.datePickerMinDate }
                    max={ this.props.datePickerMaxDate }
                    onChange = { this.props.datePickerChangeAction }
                    onBlur={ this.onBlurFieldHandler }
                    disabled={ this.props.datePickerIsDissabled }
                />
            </div>
        );
    }

    clickFieldHandler(event){
        this.setState({ fieldType: "date" });
    }

    onBlurFieldHandler(event){
        if(event.target.value.length === 0){
            this.setState({ fieldType: "input" });
        }
        if(this.props.datePickerBlurAction){
            this.props.datePickerBlurAction(event);
        }
    }

}

export default React.memo(DatePickerComponent);

【问题讨论】:

  • 您使用哪个日期选择器库?请提供更多信息。
  • @MikhailGrechka 我正在使用 moment.js 日期库
  • @Vins98 DatePickerComponentmoment.js 无关,它要么是您的自定义组件,要么来自某个库。这是什么?
  • 请展示您的组件
  • @MikhailGrechka 很抱歉之前没有提供所有信息。我现在更新了问题并包含了我的组件

标签: javascript reactjs momentjs


【解决方案1】:

我目前正在使用矩库来更改日期格式

时刻('03/03/2021').format('YYYY-MM-DD')

【讨论】:

  • 我也试过了,但格式仍然是 MM/DD/YYYY,即使我给出的格式是 YYYY/MM/DD
  • 您使用的是哪个库版本?或者你可以试试 let date = "2018-06-02T10: 00: 00" let correctDate = moment(date, 'YYYY-MM-DDTHH: mm: ss').format('YYYY-MM-DD HH:mm ') 以格式传递日期
  • 我用的是^2.29.1版本
  • 是的,我使用的版本与此解决方案相同
猜你喜欢
  • 2019-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多