Reputation:
I have a string like this String dt = '04-09-2021 - 15:00'
i want to convert it into local time zone
and my code is:
if(dt != 'Not Available'){
return DateFormat('dd-MM-yyyy - HH:mm')
.format(DateTime.parse(dt).toLocal())
.toString();
}else{
return dt;
}
But i get the error: Invalid date format 04-09-2021 - 15:00
Upvotes: 1
Views: 4057
Reputation: 12575
Here I wrote a dateformatter and convert it to local time. As well as you can format like as you wish.
// call getFormattedDateFromFormattedString function in Text
Center(
child: Text(getFormattedDateFromFormattedString(
currentFormat: "dd-MM-yyyy - HH:mm",
desiredFormat: "dd MMM yyyy HH:mm a",
value: "04-09-2000 - 15:00")),
)
// date fomatter function
String getFormattedDateFromFormattedString(
{@required String currentFormat,
@required String desiredFormat,
String value}) {
String formattedDate = "";
if (value != null || value.isNotEmpty) {
try {
DateTime dateTime = DateFormat(currentFormat).parse(value, true).toLocal();
formattedDate = DateFormat(desiredFormat).format(dateTime);
} catch (e) {
print("$e");
}
}
// print("Formatted date time: $formattedDate");
return formattedDate.toString();
}
Output:
N.B: My time zone GMT+6.0
Upvotes: 0
Reputation: 510
You should use parse, not format, the format functions receive a date, but you don't have a date, you have an string, use:
DateFormat('dd-MM-yyyy - HH:mm').parse(dt);
Upvotes: 3