I have a simple app in which I can pick a date and also a time:
Both fields return DateTime Objects.
What I’m looking for is a good practices to combine the date and the time to a new DateTime object.
What I’ve done is I create a function:
void combineDateAndTime({int? year, int? month, int? day, int? hour, int? min, int? sec}) {
if (year != null) {
dt = DateTime(
year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.millisecond, dt.microsecond);
}
if (month != null) {
dt = DateTime(
dt.year, month, dt.day, dt.hour, dt.minute, dt.second, dt.millisecond, dt.microsecond);
}
if (day != null) {
dt = DateTime(
dt.year, dt.month, day, dt.hour, dt.minute, dt.second, dt.millisecond, dt.microsecond);
}
if (hour != null) {
dt = DateTime(
dt.year, dt.month, dt.day, hour, dt.minute, dt.second, dt.millisecond, dt.microsecond);
}
if (min != null) {
dt = DateTime(
dt.year, dt.month, dt.day, dt.hour, min, dt.second, dt.millisecond, dt.microsecond);
}
if (sec != null) {
dt = DateTime(
dt.year, dt.month, dt.day, dt.hour, sec, dt.second, dt.millisecond, dt.microsecond);
}
}
And by selection a date I call the function with:
combineDateAndTime(day: date.day, month: date.month, year: date.year);
And for selecting a time:
combineDateAndTime(hour: date.hour, min: date.minute);
But I thing there should be a better solution to do this…
2
Answers
Instead of all
if
condition you can change yourcombineDateAndTime
to this:When you get the Date, add it to your DateTime variable like this:
Then when you get time, add it to the variable like this: