为什么 React Native 中的 new Date('DD-MM-YYYY') 返回错误的日期?

问题描述 投票:0回答:1

我正在使用 dayjs,我有一个输入字段,用户可以在其中输入日期或从选择器中选择一个日期,如果我使用 DD-MM-YYYY 格式,则会出现一个问题,一开始我认为这只会发生在 dayjs 上,但是当我用原生 Date() 进行了测试,发生了同样的问题 我尝试做

console.log(new Date('01-01-2023'));
这显示了
0006-07-16T02:00:00+02:00

如果我使用 YYYY-MM-DD 格式,它可以工作,但我不明白是什么导致了这个问题。 Android 和 iOS 上都发生这种情况

跑步

npx react-native info

System:
  OS: macOS 14.2
  CPU: (12) arm64 Apple M2 Max
  Memory: 77.72 MB / 32.00 GB
  Shell:
    version: "5.9"
    path: /bin/zsh
Binaries:
  Node:
    version: 20.10.0
    path: /usr/local/bin/node
  Yarn:
    version: 4.0.2
    path: ~/.nvm/versions/node/v20.10.0/bin/yarn
  npm:
    version: 10.2.3
    path: ~/.nvm/versions/node/v20.10.0/bin/npm
  Watchman:
    version: 2023.12.04.00
    path: /opt/homebrew/bin/watchman
Managers:
  CocoaPods:
    version: 1.14.3
    path: /Users/myuser/.rbenv/shims/pod
SDKs:
  iOS SDK:
    Platforms:
      - DriverKit 23.2
      - iOS 17.2
      - macOS 14.2
      - tvOS 17.2
      - watchOS 10.2
  Android SDK:
    Android NDK: 22.1.7171670
IDEs:
  Android Studio: 2023.1 AI-231.9392.1.2311.11076708
  Xcode:
    version: 15.1/15C65
    path: /usr/bin/xcodebuild
Languages:
  Java:
    version: 17.0.9
    path: /usr/bin/javac
  Ruby:
    version: 2.6.10
    path: /usr/bin/ruby
npmPackages:
  "@react-native-community/cli": Not Found
  react:
    installed: 18.2.0
    wanted: 18.2.0
  react-native:
    installed: 0.72.3
    wanted: 0.72.3
  react-native-macos: Not Found
npmGlobalPackages:
  "*react-native*": Not Found
Android:
  hermesEnabled: true
  newArchEnabled: false
iOS:
  hermesEnabled: true
  newArchEnabled: false
react-native date
1个回答
0
投票
const currentDate = new Date();
       const GivenDate = new Date(baseStore.scooterListByID.createdOn);
       const differenceInTime = currentDate.getTime() - GivenDate.getTime();
       const differenceInDays = Math.round(differenceInTime / (1000 * 3600 * 24));

例如,在上面的代码中,我使用 getTime() 将两个日期转换为毫秒。然后我进行必要的数学运算除法。除此之外,我针对你提出的问题做了一些研究。解决方案可能是:

console.log(new Date('January 01,2023))
console.log(new Date(2023,1,1))
如果你这样写,我希望它会产生结果。

© www.soinside.com 2019 - 2024. All rights reserved.