I getting below date time from server
"datetime":"2020-07-17T03:18:31.177769-04:00"
and I'm using below code to parse to get time from above date
var format = DateFormat('HH:mm a');
debugPrint('LocalTime ${format.parse(timeZoneData.datetime)}');
I'm getting below exception
flutter: Error 123: FormatException: Trying to read : from 2020-07-17T03:22:09.959577-04:00 at position 5
and i want display the above time like this 3:18 AM
Can anybody know how can parse date time in flutter
If need more information please do let me know. Thanks in advance. Your efforts will be appreciated.
Your problem is you are trying to parse "2020-07-17T03:18:31.177769-04:00"
with the pattern "HH:mm a"
which is impossible since the pattern are not even close to the provided string.
Instead, what you properly want is to parse your datetime string into a DateTime
object and use your DateFormat
to convert the DateTime
into a String
. Since your provided datetime string are formatted in a format which dart can parse out of the box, we can just use DateTime.parse
.
An example on this can be seen here:
import 'package:intl/intl.dart';
void main() {
const dateTimeString = '2020-07-17T03:18:31.177769-04:00';
final dateTime = DateTime.parse(dateTimeString);
final format = DateFormat('HH:mm a');
final clockString = format.format(dateTime);
print(clockString); // 07:18 AM
}
About the clock, it will by default parse the datetime into UTC if there are provided a timezone in the string like the example.
You can output local time by doing:
final clockString = format.format(dateTime.toLocal());
But this solution will of course only work if your own computer has the timezone offset "-04:00". But it will be the most correct solution since the inner state of the DateTime
is correct.
If you want to parse the datetime string directly to local time I think the easiest way is to remove the timezone part of your datetime string like:
final dateTime = DateTime.parse(dateTimeString.replaceFirst(RegExp(r'-\d\d:\d\d'), ''));
This will give a DateTime
object which contains local time and will print your timestamp as you want:
import 'package:intl/intl.dart';
void main() {
const dateTimeString = '2020-07-17T03:18:31.177769-04:00';
final dateTime =
DateTime.parse(dateTimeString.replaceFirst(RegExp(r'-\d\d:\d\d'), ''));
final format = DateFormat('HH:mm a');
final clockString = format.format(dateTime);
print(clockString); // 03:18 AM
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With