detectDateFormat static method

String detectDateFormat(
  1. String dateString
)

Implementation

static String detectDateFormat(String dateString){

  HashMap matchHash = HashMap<String, String>();
  matchHash["xxxxxxxx_xxxxxx"] = "yyyyMMdd_HHmmss";
  matchHash["xxxxxxxx xxxxxx"] = "yyyyMMdd HHmmss";
  matchHash["xxxx-xx-xx xx:xx:xx"] = "yyyy-MM-dd HH:mm:ss";
  matchHash["xxxx-xx-xx xx:xx"] = "yyyy-MM-dd HH:mm";
  matchHash["xxxx/xx/xx xx:xx:xx"] = "yyyy/MM/dd HH:mm:ss";
  matchHash["xxxx/xx/xx xx:xx"] = "yyyy/MM/dd HH:mm";
  matchHash["xx-xx-xxxx xx:xx:xx"] = "dd-MM-yyyy HH:mm:ss";
  matchHash["xx-xx-xxxx xx:xx"] = "dd-MM-yyyy HH:mm";
  matchHash["xx/xx/xxxx xx:xx:xx"] = "dd/MM/yyyy HH:mm:ss";
  matchHash["xx/xx/xxxx xx:xx"] = "dd/MM/yyyy HH:mm";
  matchHash["xxxx-xx-xx"] = "yyyy-MM-dd";
  matchHash["xxxx/xx/xx"] = "yyyy/MM/dd";
  matchHash["xx-xx-xxxx"] = "dd-MM-yyyy";
  matchHash["xx/xx/xxxx"] = "dd/MM/yyyy";
  matchHash["xx:xx:xx xxxx-xx-xx"] = "HH:mm:ss yyyy-MM-dd";
  matchHash["xx:xx:xx xxxx/xx/xx"] = "HH:mm:ss yyyy/MM/dd";
  matchHash["xx:xx:xx xxxx-xx-xx"] = "HH:mm:ss yyyy-MM-dd";
  matchHash["xx:xx:xx xxxx/xx/xx"] = "HH:mm:ss yyyy/MM/dd";
  matchHash["xxxx-xx-xx xx:xx"] = "yyyy-MM-dd HH:mm";
  matchHash["xxxx/xx/xx xx:xx"] = "yyyy/MM/dd HH:mm";
  matchHash["xx:xx"] = "HH:mm";
  matchHash["xx:xx xx"] = "hh:mm a";
  matchHash["xx xxx xxxx"] = "dd MMM yyyy";
  matchHash["x xxx xxxx"] = "d MMM yyyy";
  matchHash["xxxx xxx xx"] = "yyyy MMM dd";
  matchHash["xxxx xxx x"] = "yyyy MMM d";

  final regex = RegExp("[0-9]");
  final regexAlphabets = RegExp("[a-z]");
  final regexAlphabetsCaps = RegExp("[A-Z]");
  var numberRemovedString = dateString.replaceAll(regex,"x");
  numberRemovedString = numberRemovedString.replaceAll(regexAlphabets, "x");
  numberRemovedString = numberRemovedString.replaceAll(regexAlphabetsCaps, "x");
  final targetFormat = matchHash[numberRemovedString];

  if(targetFormat != null){
  return targetFormat;
  }

  return "yyyy-MM-dd HH:mm:ss";
}