首页 > 解决方案 > 使用时刻更改日期格式

问题描述

我正在使用具有 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);

标签: javascriptreactjsmomentjs

解决方案


我目前正在使用时刻库​​来更改日期格式,例如

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


推荐阅读