如何自定义new Date()格式,将React Native状态设为DD/MM/YYYY
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) become05or09instead 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:
- First install the library:
npm install date-fns # or yarn add date-fns
- Then import the
formatfunction 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

