I’m getting the string "enddate" from my django backend api in the following format :
"enddate" : "2024-08-24T05:30:00+05:30"
My purpose is to convert it to Datetime in my flutter app in the following forma:
dd/MM/yyyy i.e 24/08/2024
so that it becomes easy to read for the users.
Based on the several stack posts i have read,I have figured the following function but I cant seem to figure to use DateFormat function in the correct manner for the input date. Here is what i have tried :
DateTime parseEndDate(String enddate) {
var inputFormat = DateFormat('yy/MM/dd');
var inputDate = inputFormat.parse(enddate.toString()); // <--yy/MM/dd format
var outputFormat = DateFormat('dd/MM/yyyy');
var outputDate = outputFormat.format(inputDate); // <-- dd/MM/yy format
return DateTime.parse(outputDate).toLocal();
}
4
Answers
Rewrite the function such that it will parse the date string to DateTime and return the String of your desired format
Try below code:
With Package – intl
With out Package
Your
parseEndDate
function has the following two issues:var inputFormat = DateFormat('yy/MM/dd');
is incorrect because the format of theenddate
string isyyyy-MM-dd
.outputFormat
(dd/MM/yyyy
) cannot be repeatedly parsed to aDateTime
object.You can write the following string extension functions to get either a formatted date string or a
DateTime
object:Then use it like this:
Your returned datetime is in ISO 8601 format, so Flutter can easy to parse it to datetime object using DateTime.parse() method. This method automatically handles the ISO 8601 format, including the timezone offset.