|
| 1 | +import React from 'react'; |
| 2 | +import { Component, PropTypes } from '../utils/'; |
| 3 | + |
| 4 | +function formatDate(date, formatStr) { |
| 5 | + date = new Date(date) |
| 6 | + let timeFormat = { |
| 7 | + "M+": date.getMonth() + 1, //month |
| 8 | + "d+": date.getDate(), //day |
| 9 | + "h+": date.getHours(), //hour |
| 10 | + "m+": date.getMinutes(), //minute |
| 11 | + "s+": date.getSeconds(), //second |
| 12 | + "q+": Math.floor((date.getMonth() + 3) / 3), //quarter |
| 13 | + "S": date.getMilliseconds() //millisecond |
| 14 | + } |
| 15 | + if (/(y+)/.test(formatStr)) formatStr = formatStr.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); |
| 16 | + for (let k in timeFormat) { |
| 17 | + if (new RegExp("(" + k + ")").test(formatStr)) { |
| 18 | + formatStr = formatStr.replace(RegExp.$1, RegExp.$1.length === 1 ? timeFormat[k] : ("00" + timeFormat[k]).substr(("" + timeFormat[k]).length)); |
| 19 | + } |
| 20 | + } |
| 21 | + return formatStr; |
| 22 | +} |
| 23 | + |
| 24 | +export default class Timestamp extends Component { |
| 25 | + constructor(props) { |
| 26 | + super(props); |
| 27 | + this.state = { |
| 28 | + date: "" |
| 29 | + } |
| 30 | + } |
| 31 | + componentDidMount() { |
| 32 | + const { value, format } = this.props |
| 33 | + this.setState({ |
| 34 | + date: formatDate(value, format) |
| 35 | + }) |
| 36 | + } |
| 37 | + componentWillReceiveProps(nextProps) { |
| 38 | + if (nextProps.value !== this.props.value || nextProps.format !== this.props.format) { |
| 39 | + this.setState({ |
| 40 | + date: formatDate(nextProps.value, nextProps.format) |
| 41 | + }) |
| 42 | + } |
| 43 | + } |
| 44 | + render() { |
| 45 | + const { prefixCls, className, ...resetProps } = this.props; |
| 46 | + const { date } = this.state; |
| 47 | + return ( |
| 48 | + <span className={this.classNames(`${prefixCls}`, className)} {...resetProps}> |
| 49 | + {date} |
| 50 | + </span> |
| 51 | + ) |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +Timestamp.propTypes = { |
| 56 | + prefixCls: PropTypes.string, |
| 57 | + value: PropTypes.oneOfType([ |
| 58 | + PropTypes.string, // ISO-8601 string |
| 59 | + PropTypes.object // Date object |
| 60 | + ]).isRequired, |
| 61 | + format: PropTypes.string, |
| 62 | +} |
| 63 | + |
| 64 | +Timestamp.defaultProps = { |
| 65 | + prefixCls: 'w-timestamp', |
| 66 | + format: 'yyyy-MM-dd hh:mm:ss', |
| 67 | +} |
0 commit comments