问题
I have a DateTime
and I'm trying to do two things with it. 1: Only update the date and month. 2: Only update the time. How can I achieve that?
DateTime currentDateTime = DateTime.now();
void updateTime(DateTime newTime) {
currentDateTime = ?
}
void updateDate(DateTime newTime) {
currentDateTime = ?
}
Is there any way I can destruct the currentDateTime
like DateTime(...currentDateTime, ..newTime)
回答1:
Construct your Datetime object from Datetime.now() properties, instead of the whole Datetime.now() object. This should work.
DateTime currentDateTime = DateTime.now();
void updateTime(DateTime currentDateTime, DateTime newTime) {
currentDateTime = DateTime(
year: currentDateTime.year,
month: currentDateTime.month
day: currentDateTime.day,
hour: newTime.hour,
minute: newTime.minute,
second: newTime.second,
);
}
void updateDate(DateTime currentDateTime, DateTime newDate) {
currentDateTime = DateTime(
year: currentDateTime.year,
month: newTime.month
day: newTime.day,
hour: currentDateTime.hour,
minute: currentDateTime.minute,
second: currentDateTime.second,
);
}
Remember the constructor of Datetime looks like this
DateTime(int year, [int month = 1, int day = 1, int hour = 0, int minute = 0, int second = 0, int millisecond = 0, int microsecond = 0])
回答2:
To only update time you can use TimeOfDay
. This is approach that I can do
DateTime currentDateTime = DateTime.now();
void updateTime(TimeOfDay newTime) {
// 2020-09-07 09:03:24.469
TimeOfDay time = TimeOfDay(hour: newTime.hour, minute: newTime.minute);
currentDateTime = DateTime(currentDateTime.year, currentDateTime.month, currentDateTime.month, time.hour, time.minute);
// 2020-09-09 15:00:00.000
}
void updateDate(DateTime newTime) {
// 2020-09-09 15:00:00.000
currentDateTime = DateTime(newTime.year, newTime.month, newTime.day);
// 2021-01-01 00:00:00.000
}
I hope this is helpful.
来源:https://stackoverflow.com/questions/63770437/how-to-only-change-the-time-in-datetime