You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用Airbnb的react-dates库singleDatePicker组件时出现date.format is not a function错误

Fixing the date.format is not a function Error in react-dates SingleDatePicker

Hey there! That error is super common when working with react-dates—let’s break down what’s going on and how to fix it.

Why This Happens

react-dates relies entirely on moment.js for date handling and formatting. The date.format is not a function error pops up because the component is receiving a date that isn’t a moment object (like a native JavaScript Date instance, which doesn’t have a .format() method built-in).

Step-by-Step Fix

  1. Install Moment.js (if you haven’t already)
    Run this in your project directory to add the dependency:

    npm install moment
    # or
    yarn add moment
    
  2. Import Moment in Your Component
    At the top of your component file, import moment to work with dates:

    import moment from 'moment';
    
  3. Ensure Your Date State Uses Moment Objects
    When initializing your selected date state, use a moment object (or null for no initial selection). When handling the date change, the onDateChange callback from react-dates already returns a moment object—just save it directly to state:

    import React, { useState } from 'react';
    import { SingleDatePicker } from 'react-dates';
    import 'react-dates/lib/css/_datepicker.css';
    import moment from 'moment';
    
    function YourComponent() {
      // Initialize with null or a moment date (e.g., moment() for today)
      const [selectedDate, setSelectedDate] = useState(null);
      const [isFocused, setIsFocused] = useState(false);
    
      return (
        <SingleDatePicker
          date={selectedDate}
          onDateChange={(newDate) => setSelectedDate(newDate)}
          focused={isFocused}
          onFocusChange={({ focused }) => setIsFocused(focused)}
          id="single-date-picker" // Required unique ID
        />
      );
    }
    
    export default YourComponent;
    

Quick Checks to Avoid Future Issues

  • Double-check you’re not passing a native Date object to the date prop. If you need to convert a native Date to moment, use moment(yourNativeDate).
  • Make sure your versions of react-dates and moment are compatible—most recent versions of react-dates work with the latest moment releases.
  • Don’t modify the moment object returned by onDateChange directly; just pass it straight to your state setter.

That should resolve the date.format is not a function error and get your SingleDatePicker working smoothly!

内容的提问来源于stack exchange,提问作者Aashiq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 15:54:08