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

如何自定义new Date()格式,将React Native状态设为DD/MM/YYYY

解决React Native DateTime Picker日期格式化问题

Hey there! I get that you're using react-native-modal-datetime-picker and want to convert the selected date into the DD/MM/YYYY format instead of the default long string like Sun Jul 18 2020 18:21:15 GMT+04:00. Let's break down two easy ways to fix this:

方法1:手动格式化(无需额外依赖)

You can extract the day, month, and year from the Date object directly, then format them into the desired string. Just make sure to pad single-digit values with a leading zero to keep the consistent DD/MM/YYYY format:

handleConfirmDate(date) {
  // Get day, month, year from the Date instance
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed, so add 1!
  const year = date.getFullYear();
  
  // Combine into DD/MM/YYYY format
  const formattedDate = `${day}/${month}/${year}`;
  
  this.setState({ date: formattedDate });
}
  • padStart(2, '0') ensures that single-digit days/months (like 5 or 9) become 05 or 09 instead of staying as single digits.
  • Remember: JavaScript's getMonth() returns a 0-based index (January = 0, December = 11), so we add 1 to get the correct calendar month.

方法2:使用日期处理库(更简洁)

If you plan to do more date-related operations later, using a lightweight library like date-fns is a great choice. Here's how to use it:

  1. First install the library:
npm install date-fns
# or
yarn add date-fns
  1. Then import the format function and use it in your handler:
import { format } from 'date-fns';

handleConfirmDate(date) {
  // Format the date directly using the 'dd/MM/yyyy' pattern
  const formattedDate = format(date, 'dd/MM/yyyy');
  this.setState({ date: formattedDate });
}

This method is cleaner and less error-prone, especially if you need to handle different date formats or time zones later.

小提示:Avoid using Moment.js since it's now in maintenance mode (no new features). date-fns or Luxon are better modern alternatives.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:27:43