Happy New Year!

react日期格式化组件

最近在项目中经常碰到日期格式化的转化,如默认时间格式转换为“2020-02-02”或“2020-02-02”转换成“2020/02/02”等等,根据需要我总结了以下几种格式:

YYYY-MM-DD、YYYY/MM/DD、MM-DD-YYYY、MM/DD/YYYY、YYYY年MM月DD日

下面是js逻辑:

import React from 'react';
import PropTypes from "prop-types";

// 导出方法一
export function dateFormat(format, date) {
  // format=>日期格式  date=>要格式化的时间 
  let time = new Date();
  if (date) {
    if (typeof date === 'string') {
      const dateTemp = date.substr(0,4) + ',' + date.substr(4,2) + ',' + date.substr(6);
      time = new Date(dateTemp);
    } else {
      time = new Date(date);
    }
  }
  let year = time.getFullYear();
  let month = time.getMonth() + 1;
  let day = time.getDate();

  /* istanbul ignore else */
  if (month < 10) {
    month = '0' + month;
  }
  /* istanbul ignore else */
  if (day < 10) {
    day = '0' + day;
  }
  let result = '';
  switch(format) {
    case 'YYYY-MM-DD' : {
      return year + '-' + month + '-' + day;
    }
    case 'YYYY/MM/DD' : {
      return year + '/' + month + '/' + day;
    }
    case 'MM-DD-YYYY' : {
      return month + '-' + day + '-' + year;
    }
    case 'MM/DD/YYYY' : {
      return month + '/' + day + '/' + year;
    }
    case 'YYYY年MM月DD日' : {
      return year + '年' + month + '月' + day + '日';
    }
    default: {
      return result;
    }
  }
}

// 导出方法二(依赖方法一)
export function DateFormat(props) {
  return(
    <span>{dateFormat(props.format, props.date)}</span>
  );
}


DateFormat.propTypes = {
  format: PropTypes.oneOf(['YYYY-MM-DD', 'YYYY/MM/DD', 'MM-DD-YYYY', 'MM/DD/YYYY', 'YYYY年MM月DD日']),
  date: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string,
  ]),
};

DateFormat.defaultProps = {
  format: 'YYYY-MM-DD',
};

export default DateFormat;

  

项目中调用方法:

import { DateFormat, dateFormat } from 'xxxx/xxxx';

<DateFormat format="YYYY/MM/DD" date={new Date()} />

{dateFormat("YYYY-MM-DD", new Date())}

 

根据自己的需要应用到项目中吧!

posted @ 2020-03-15 19:43  一只看夕阳的猫  阅读(2997)  评论(0编辑  收藏  举报
返回顶部小火箭
世界很公平,想要最好,就一定得付出!
x
博客主页