How do convert String to DateTime in flutter

 Hello friends today we will get some new things in flutter like how can we convert any String in to DateTime with dateTime Format thats very easy


first of all we taking a list for a month which get from our string like that

    List months = [
'',
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
after taking a list of month split your string to ("-") so now you got an array with 3 items one as a date, one as month, one as year
 
static String stringToDate(String formattedString) {
List months = [
'',
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec'
];
    Now you can convert your string to date
  var date = DateTime(int.parse(da[2]), month, int.parse(da[0]));

this is a method where you are puting date,month and year here and you got a full date with DateTime dataType


you can check an exmaple below




    var month = 1;
var da = formattedString.split("-");
if (da[1] == "Jan")
month = 1;
else if (da[1] == "Feb")
month = 2;
else if (da[1] == "Mar")
month = 3;
else if (da[1] == "Apr")
month = 4;
else if (da[1] == "May")
month = 5;
else if (da[1] == "Jun")
month = 6;
else if (da[1] == "Jul")
month = 7;
else if (da[1] == "Aug")
month = 8;
else if (da[1] == "Sep")
month = 9;
else if (da[1] == "Oct")
month = 10;
else if (da[1] == "Nov")
month = 11;
else if (da[1] == "Dec") month = 12;
var date = DateTime(int.parse(da[2]), month, int.parse(da[0]));

var formattedDate = Widgets.apiDateFormat(date);
return formattedDate;
}

Comments

Popular Posts