可以使用DatePicker
组件来创建日期选择器,并使用moment
库来处理日期和时间。
首先,安装moment
库,可以使用以下命令:
npm install moment
然后,可以使用以下代码示例来保存日期选择器中的当前时间,以便作为本地通知的提醒时间:
import React, { useState } from 'react';
import { View, Button, DatePickerAndroid, Platform } from 'react-native';
import moment from 'moment';
const App = () => {
const [reminderTime, setReminderTime] = useState(null);
const showDatePicker = async () => {
try {
const { action, year, month, day } = await DatePickerAndroid.open({
date: new Date(),
});
if (action !== DatePickerAndroid.dismissedAction) {
const selectedDate = moment({ year, month, day });
const currentTime = moment();
// Combine selected date with current time
const selectedTime = selectedDate.set({
hour: currentTime.get('hour'),
minute: currentTime.get('minute'),
second: currentTime.get('second'),
});
setReminderTime(selectedTime);
}
} catch ({ code, message }) {
console.warn('Cannot open date picker', message);
}
};
// Function to schedule local notification using reminderTime
return (
);
};
export default App;
上述代码中,我们使用DatePickerAndroid
组件打开日期选择器,并获取用户选择的年、月、日。然后,我们使用moment
库将选择的日期与当前时间组合起来,以获取完整的提醒时间。最后,我们将提醒时间保存在reminderTime
状态中,以供后续使用。
请注意,上述代码仅适用于React Native环境,并且仅支持Android平台。如果您需要在其他平台或使用其他框架中实现相同的功能,请根据具体情况进行调整。