I can format the time in my desired format "3:38 PM" but it’s a string type. But I want my to DateTime for later calculations. I can’t manage to parse them. I want to remove this "1970-01-01" from the datetime 1970-01-01 03:38:00.000
I want this string to "3:38 PM" -> this DateTime "03:38:00.000". How can I do that?
import 'package:intl/intl.dart';
void main() {
String timeStr = "3:38 PM";
try {
DateTime parsedTime = DateFormat("HH:mm a").parse(timeStr);
print(parsedTime); // 1970-01-01 15:38:00.000
String formattedTime = DateFormat("h:mm a").format(parsedTime);
print(formattedTime); // Output: 3:38 PM
} catch (e) {
print("Invalid time format");
}
}
2
Answers
You can’t create a
DateTime
object without the date part. If you don’t pass the date part and tries to parse the string to DateTime, Dart automatically adds epoch date (1970-01-01) to the object.Two possible work arounds are:
Hope this helps 🙂
As said in the class you’re using, it’s a DateTime, so it’s using a date alongside the time of the day, which defaults to 1970-01-01. If you only need hours and minutes (so no seconds, milliseconds…), you could be using TimeOfDay class: