formatDate function

String formatDate (
  1. {@required DateTime date,
  2. String format: "MMDDYYYY",
  3. String divider: "/"}
)

Formats DateTime into a # string with the date.

Ex. output is "12/04/2019".

Can be given 'MM' 'DD' and 'YYYY' OR 'YY' in any order for format (ex. 'MMDDYY' 'YYYYDDMM' 'DDYYYYMM' 'MMDD' 'MMYYYY').

Can be given any divider (ex. '/' ':' '.').

Implementation

String formatDate(
    {@required DateTime date,
    String format = "MMDDYYYY",
    String divider = "/"}) {
  var day = date.day;
  var month = date.month;
  var year = date.year;
  String returner = "";
  bool isLastYear = false;
  for (var l = 0; l < format.length; l += 2) {
    if (l != 0) {
      returner = returner + divider;
    }
    switch (format[l]) {
      case "M": {
        isLastYear = false;
        if (month >= 10) {
          returner = returner + '$month';
        } else {
          returner = returner + '0$month';
        }
      }
      break;
      case "D": {
        isLastYear = false;
        if (day >= 10) {
          returner = returner + '$day';
        } else {
          returner = returner + '0$day';
        }
      }
      break;
      case "Y": {
        if (!isLastYear) {
          if (int.parse(year.toString().substring(2)) >= 10) {
            returner = returner + year.toString().substring(2);
          } else {
            returner = returner + '0' + year.toString().substring(2);
          }
          isLastYear = true;
        } else {
          returner =
              returner.substring(0, returner.length - 3) + '$year';
          isLastYear = true;
        }
      }
      break;
      default: {
        throw ArgumentError("Invalid format passed!");
      }
    }
  }
  return returner;
}