public static DateTime ToDateTime(this string str, FormatoDataHora from, FormatoDataHora to) { string value = str.OnlyNumbers(); DateTime d = DateTime.Now; if (from == FormatoDataHora.ddMMyyyyHHmmss && to == FormatoDataHora.yyyyMMddHHmmss) { if (DateTime.TryParse(str, out d)) { return(d); } // 01 01 2019 00 00 00 // 01 23 4567 89 01 23 return(new DateTime(Convert.ToInt32(value.Substring(4, 4)), Convert.ToInt32(value.Substring(2, 2)), Convert.ToInt32(value.Substring(0, 2)), Convert.ToInt32(value.Substring(8, 2)), Convert.ToInt32(value.Substring(10, 2)), Convert.ToInt32(value.Substring(12, 2)))); } if (from == FormatoDataHora.yyyyMMdd && to == FormatoDataHora.yyyyMMddHHmmss) { if (DateTime.TryParse(str, out d)) { return(d); } // 2019 09 27 // 0123 45 67 return(new DateTime(Convert.ToInt32(value.Substring(0, 4)), Convert.ToInt32(value.Substring(4, 2)), Convert.ToInt32(value.Substring(6, 2)), 0, 0, 0)); } return(new DateTime()); }
public static DateTime ToDateTime(this string str, FormatoDataHora format) { string value = str.OnlyNumbers(); switch (format) { case FormatoDataHora.ddMMyyyyHHmmss: if (value.Length != 14) { break; } return(new DateTime(Convert.ToInt32(value.Substring(4, 4)), Convert.ToInt32(value.Substring(2, 2)), Convert.ToInt32(value.Substring(0, 2)), Convert.ToInt32(value.Substring(8, 2)), Convert.ToInt32(value.Substring(10, 2)), Convert.ToInt32(value.Substring(12, 2)))); default: break; } return(new DateTime()); }