Reputation: 974
I have a date and time picker:
Future<void> _showDatePicker(BuildContext context) async {
final picked = await showDatePicker(
context: context,
initialDate: _fromDate,
firstDate: DateTime(1000, 1),
lastDate: DateTime(2200),
);
print(picked);
if (picked != null && picked != _fromDate) {
setState(() {
_fromDate = picked;
});
}
}
Future<void> _showTimePicker(BuildContext context) async {
final picked = await showTimePicker(
context: context,
initialTime: _fromTime,
);
print(picked);
if (picked != null && picked != _fromTime) {
setState(() {
_fromTime = picked;
});
}
}
When I pick a date, the result is 2021-03-10 00:00:00.000
and when I pick a time, the result is TimeOfDay(22:12)
.
How do I combine both of them to have 2021-03-10 22:12:00.000
. That's what I want to save to my database.
And how do I remove the three trailing zeros from the date 2021-03-10 00:00:00.000
of so it can look like this --> 2021-03-10 00:00:00
when displaying it in a Text()
widget?
Upvotes: 0
Views: 1115
Reputation: 1654
After selecting the date and time, you must generate a new datetime object in this way.
DateTime _fromDate = new DateTime.now();
TimeOfDay _fromTime = new TimeOfDay.now();
DateTime newDateTime = new DateTime(_fromDate.year, _fromDate.month,
_fromDate.day, _fromTime.hour, _fromTime.minute);
Then use the intl package to format the date to the string you want.
String dateTimeFormated = DateFormat('yyyy-MM-dd H:mm:ss').format(newDateTime);
print(dateTimeFormated);
Result will be a string similar to this
2021-03-10 22:12:00
Upvotes: 1