DatePicker 日期选择

用于选择日期或者时间。

规则

  • 最多展示 5 个独立滚轮,每个滚轮表示一个不同的值。

代码演示

基本

  1. import { DatePicker, List } from 'antd-mobile';
  2. import enUs from 'antd-mobile/lib/date-picker/locale/en_US';
  3. const nowTimeStamp = Date.now();
  4. const now = new Date(nowTimeStamp);
  5. // GMT is not currently observed in the UK. So use UTC now.
  6. const utcNow = new Date(now.getTime() + (now.getTimezoneOffset() * 60000));
  7. // Make sure that in `time` mode, the maxDate and minDate are within one day.
  8. let minDate = new Date(nowTimeStamp - 1e7);
  9. const maxDate = new Date(nowTimeStamp + 1e7);
  10. // console.log(minDate, maxDate);
  11. if (minDate.getDate() !== maxDate.getDate()) {
  12. // set the minDate to the 0 of maxDate
  13. minDate = new Date(maxDate.getFullYear(), maxDate.getMonth(), maxDate.getDate());
  14. }
  15. function formatDate(date) {
  16. /* eslint no-confusing-arrow: 0 */
  17. const pad = n => n < 10 ? `0${n}` : n;
  18. const dateStr = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
  19. const timeStr = `${pad(date.getHours())}:${pad(date.getMinutes())}`;
  20. return `${dateStr} ${timeStr}`;
  21. }
  22. // If not using `List.Item` as children
  23. // The `onClick / extra` props need to be processed within the component
  24. const CustomChildren = ({ extra, onClick, children }) => (
  25. <div
  26. onClick={onClick}
  27. style={{ backgroundColor: '#fff', height: '45px', lineHeight: '45px', padding: '0 15px' }}
  28. >
  29. {children}
  30. <span style={{ float: 'right', color: '#888' }}>{extra}</span>
  31. </div>
  32. );
  33. class Demo extends React.Component {
  34. state = {
  35. date: now,
  36. time: now,
  37. utcDate: utcNow,
  38. dpValue: null,
  39. customChildValue: null,
  40. visible: false,
  41. }
  42. render() {
  43. return (
  44. <List className="date-picker-list" style={{ backgroundColor: 'white' }}>
  45. <DatePicker
  46. value={this.state.date}
  47. onChange={date => this.setState({ date })}
  48. >
  49. <List.Item arrow="horizontal">Datetime</List.Item>
  50. </DatePicker>
  51. <DatePicker
  52. mode="date"
  53. title="Select Date"
  54. extra="Optional"
  55. value={this.state.date}
  56. onChange={date => this.setState({ date })}
  57. >
  58. <List.Item arrow="horizontal">Date</List.Item>
  59. </DatePicker>
  60. <DatePicker
  61. mode="time"
  62. minuteStep={2}
  63. use12Hours
  64. value={this.state.time}
  65. onChange={time => this.setState({ time })}
  66. >
  67. <List.Item arrow="horizontal">Time (am/pm)</List.Item>
  68. </DatePicker>
  69. <DatePicker
  70. mode="time"
  71. minDate={minDate}
  72. maxDate={maxDate}
  73. value={this.state.time}
  74. onChange={time => this.setState({ time })}
  75. >
  76. <List.Item arrow="horizontal">Limited time</List.Item>
  77. </DatePicker>
  78. <DatePicker
  79. mode="time"
  80. locale={enUs}
  81. format={val => `UTC Time: ${formatDate(val).split(' ')[1]}`}
  82. value={this.state.utcDate}
  83. onChange={date => this.setState({ utcDate: date })}
  84. >
  85. <List.Item arrow="horizontal">UTC time</List.Item>
  86. </DatePicker>
  87. <List.Item
  88. extra={this.state.dpValue && formatDate(this.state.dpValue)}
  89. onClick={() => this.setState({ visible: true })}
  90. >
  91. External control visible state
  92. </List.Item>
  93. <DatePicker
  94. visible={this.state.visible}
  95. value={this.state.dpValue}
  96. onOk={date => this.setState({ dpValue: date, visible: false })}
  97. onDismiss={() => this.setState({ visible: false })}
  98. />
  99. <DatePicker
  100. mode="time"
  101. format="HH:mm"
  102. title="Select Time"
  103. value={this.state.customChildValue}
  104. onChange={v => this.setState({ customChildValue: v })}
  105. extra="click to choose"
  106. >
  107. <CustomChildren>With customized children</CustomChildren>
  108. </DatePicker>
  109. </List>
  110. );
  111. }
  112. }
  113. ReactDOM.render(<Demo />, mountNode);
  1. .date-picker-list .am-list-item .am-list-line .am-list-extra {
  2. flex-basis: initial;
  3. }

结合 form 验证示例

日期时间选择示例, (rc-form)

  1. import { DatePicker, List, Button, InputItem } from 'antd-mobile';
  2. import { createForm } from 'rc-form';
  3. const nowTimeStamp = Date.now();
  4. const now = new Date(nowTimeStamp);
  5. const utcOffset = new Date(now.getTime() - (now.getTimezoneOffset() * 60000));
  6. // console.log(now, utcOffset, now.toISOString(), utcOffset.toISOString());
  7. class Test extends React.Component {
  8. state = {
  9. dpValue: now,
  10. idt: utcOffset.toISOString().slice(0, 10),
  11. }
  12. onSubmit = () => {
  13. this.props.form.validateFields({ force: true }, (error) => {
  14. if (!error) {
  15. console.log(this.props.form.getFieldsValue());
  16. } else {
  17. console.log(error);
  18. alert('Validation failed');
  19. }
  20. });
  21. }
  22. onReset = () => {
  23. this.props.form.resetFields();
  24. setTimeout(() => console.log(this.state), 0);
  25. }
  26. validateIdp = (rule, date, callback) => {
  27. if (isNaN(Date.parse(date))) {
  28. callback(new Error('Invalid Date'));
  29. } else {
  30. const cDate = new Date(date);
  31. const newDate = new Date(+this.state.dpValue);
  32. newDate.setFullYear(cDate.getFullYear());
  33. newDate.setMonth(cDate.getMonth());
  34. newDate.setDate(cDate.getDate());
  35. // this.setState({ dpValue: newDate });
  36. setTimeout(() => this.props.form.setFieldsValue({ dp: newDate }), 10);
  37. callback();
  38. }
  39. }
  40. validateDatePicker = (rule, date, callback) => {
  41. if (date && date.getMinutes() !== 15) {
  42. callback();
  43. } else {
  44. callback(new Error('15 is invalid'));
  45. }
  46. }
  47. render() {
  48. const { getFieldProps, getFieldError } = this.props.form;
  49. return (<form>
  50. <List
  51. className="date-picker-list"
  52. renderFooter={() => getFieldError('dp') && getFieldError('dp').join(',')}
  53. >
  54. <InputItem
  55. placeholder="must be the format of YYYY-MM-DD"
  56. error={!!getFieldError('idp')}
  57. {...getFieldProps('idp', {
  58. initialValue: this.state.idt,
  59. rules: [
  60. { validator: this.validateIdp },
  61. ],
  62. })}
  63. >Input date</InputItem>
  64. <DatePicker
  65. {...getFieldProps('dp', {
  66. initialValue: this.state.dpValue,
  67. rules: [
  68. { required: true, message: 'Must select a date' },
  69. { validator: this.validateDatePicker },
  70. ],
  71. })}
  72. >
  73. <List.Item arrow="horizontal">Date</List.Item>
  74. </DatePicker>
  75. <List.Item>
  76. <Button type="primary" size="small" inline onClick={this.onSubmit}>Submit</Button>
  77. <Button size="small" inline style={{ marginLeft: '2.5px' }} onClick={this.onReset}>Reset</Button>
  78. </List.Item>
  79. </List>
  80. </form>);
  81. }
  82. }
  83. const TestWrapper = createForm()(Test);
  84. ReactDOM.render(<TestWrapper />, mountNode);
  1. .date-picker-list .am-list-item .am-list-line .am-list-extra {
  2. flex-basis: initial;
  3. }

DatePicker日期选择 - 图1

API

属性说明类型默认值
mode日期选择的类型, 可以是日期date,时间time,日期+时间datetime,年year,月monthStringdate
value当前选中时间Date
minDate最小可选日期Datenew Date(2000, 1, 1, 0, 0, 0)
maxDate最大可选日期Datenew Date(2030, 1, 1, 23, 59, 59)
use12Hours12小时制Booleanfalse
minuteStep分钟数递增步长设置Number1
locale国际化,可覆盖全局LocaleProvider的配置Object: {DatePickerLocale: {year, month, day, hour, minute, am?, pm?}, okText, dismissText }-
disabled是否不可用Booleanfalse
onChange时间发生变化的回调函数(date: Object): void-
onValueChange每列 picker 改变时的回调(vals: any, index: number) => void-
format格式化选中的值(value: Date) => date string / format string(对应 mode 下格式分别为:YYYY-MM-DD,HH:mm,YYYY-MM-DD HH:mm)-
title弹框的标题string/React.ReactElement
extra显示文案String请选择
prefixClsclass前缀stringam-picker
className样式类名string-
onOk点击选中时执行的回调(val): void
onDismiss点击取消时执行的回调(): void
注意:日期字符串在不同浏览器有不同的实现,例如 new Date('2017-1-1') 在 Safari 上是 Invalid Date,而在 Chrome 上是能正常解析的。 注意:DatePicker children 建议是 List.Item, 如果不是,需要是自定义组件(组件内需处理 onClick / extra / children 属性,详情请看 demo