Format date using moment React

860 views Asked by At

I have created ** React Component**

class Test extends Component{

state = {
    birthdate: '2020-09-20'
}

render(){
    const {birthdate} = this.state;
    const mdiffInDays = moment(moment()).diff(moment(birthdate), 'days');
    const mdiffInWeeks = moment(moment()).diff(moment(birthdate), 'weeks');

    return(
    <div className="card">
        <span>Today: {moment(moment()).format('DD MMM YYYY')}</span>
        <span>Birthdate: {birthdate}</span>
        <span>Days: {mdiffInDays}</span>
        <span>Weeks: {mdiffInWeeks}</span>           
    </div>            
    )
}}

I got two question:

  1. Today - how instead of 23-Oct-2020 I can use "PL" region?
  2. Birthdate is render like: YYYY-MM-DD. How change this to display "DD-MM-YYY"?

I'm learning React and try to play now with dates.

1

There are 1 answers

0
anttud On BEST ANSWER

const birthdate =  '2020-09-20'
const date = new Date(birthdate)
const options = {
  year: "numeric",
  month: "short",
  day: "numeric",
};
console.log(date.toLocaleDateString("pl", options));