Reputation: 1883
I am attempting to convert the following 2HR time in String to a DateTime, so that I manage it appropriately.
"1800"
This question came close, but no one answered how to convert the String into a valid DateTime.
How to convert time stamp string from 24 hr format to 12 hr format in dart?
Attempt 1:
DateTime.parse("1800")
-
Invalid Date Format
Attempt 2:
DateTime.ParseExact("1800")
-
This doesn't seem to exist, although it shows up on various
Still no luck and need a second pair of eyes to point out the obvious to me.
Upvotes: 0
Views: 213
Reputation: 90015
DateTime.parse
expects to parse dates with times, not just times. (You can't even create a DateTime
object without a date!)
Some people generate a dummy date string, but in your case you could trivially parse it with int.parse
and then apply appropriate division and remainder operations:
var rawTime = int.parse('1800');
var hour = rawTime ~/ 100;
var minute = rawTime % 100;
Also see How do I convert a date/time string to a DateTime object in Dart? for more general DateTime
parsing.
Upvotes: 0
Reputation: 5503
The time by itself is not a datetime so you could do something like:
DateTime myTime(DateTime baseDate, String hhmm) {
assert(hhmm.length == 4, 'invalid time');
final _hours = int.parse(hhmm.substring(0, 2));
final _mins = int.parse(hhmm.substring(2, 2));
return DateTime(baseDate.year, baseDate.month, baseDate.day, _hours, _mins);
}
Upvotes: 1