【问题标题】:ReactJS - How to change the date format from an input field?ReactJS - 如何从输入字段更改日期格式?
【发布时间】:2020-11-18 04:36:33
【问题描述】:

在 react 应用程序中,我使用了一个类似的数组,

const result = [
  {firstname: "Shruthi", lastname: "R", phone: "1234567890", birthday: "24/05/1991"},
  {firstname: "Maanya", lastname: "C", phone: "8882334324", birthday: "19/07/1990"},
  {firstname: "Chethan", lastname: "Kumar", phone: "7888382222", birthday: "24/05/1995"}
];

日期输入字段是,

<input type="date" onChange={props.handleOnChange} />

handleOnChange = (e) => {
  const date = e.target.value; // getting different format here
  console.log(date);
}

基于上述,数组列表(result)中的日期输入字段和生日字段包含dd/mm/yyyy 格式,但在handleOnChange 函数中我得到的是yyyy-mm-dd 格式。

如何将日期格式更改为dd/mm/yyyy

【问题讨论】:

  • 只需使用.split('-') 将其切碎并与.join('/') 以正确的顺序缝合在一起?

标签: reactjs date events input formatting


【解决方案1】:

有一个名为 Intl.DateTimeFormat 的对象可以在 JavaScript 中启用语言敏感的日期和时间格式。您可以按照以下方式使用它并进行您想要的更改

console.log(new Intl.DateTimeFormat('en-US').format(date));

reference

【讨论】:

  • 不错的选择。一件小事,如果他们在handleOnChange 函数中得到一个字符串,那么他们需要先将其转换为日期:new Date(date)
【解决方案2】:

你可以用这个方法

let today  = new Date("2020-11-18");
today.toLocaleDateString("en-US"); // 11/18/2020
today.toLocaleDateString("en-GB"); // 18/11/2020
today.toLocaleDateString("bn-IN"); // ১৮/১১/২০২০

或者你可以使用时刻

moment(moment('2020-11-18', 'YYYY-MM-DD')).format('DD-MM-YYYY'); 

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 2018-09-29
    • 2023-03-27
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多