[英]Convert string to datetime in any format
目的 :
想要將任何格式的日期時間轉換為de-DE文化
樣本日期時間 :
2016/3/30下午2:38:20
2016/4/4上午11:08:10
我嘗試了什么
protected void Page_Load(object sender, EventArgs e)
{
string dt1Valid = CheckDateFormat("3/30/2016 2:38:20 PM");
}
public string CheckDateFormat(string checkDate)
{
string formats1 = getFormat(checkDate);
DateTime parsedDateTime;
DateTimeFormatInfo ukDtfi = new CultureInfo("de-DE", false).DateTimeFormat;
if (!DateTime.TryParseExact(checkDate, formats1, new CultureInfo("de-DE"),
DateTimeStyles.None, out parsedDateTime))
{
return Convert.ToDateTime(parsedDateTime.ToString()).ToString(ukDtfi.ShortDatePattern + " " + ukDtfi.LongTimePattern);
}
else
return "";
}
public string getFormat(string checkDate)
{
string[] formats = {"M/d/yyyy", "MM/dd/yyyy",
"d/M/yyyy", "dd/MM/yyyy",
"yyyy/M/d", "yyyy/MM/dd",
"M-d-yyyy", "MM-dd-yyyy",
"d-M-yyyy", "dd-MM-yyyy",
"yyyy-M-d", "yyyy-MM-dd",
"M.d.yyyy", "MM.dd.yyyy",
"d.M.yyyy", "dd.MM.yyyy",
"yyyy.M.d", "yyyy.MM.dd",
"M,d,yyyy", "MM,dd,yyyy",
"d,M,yyyy", "dd,MM,yyyy",
"yyyy,M,d", "yyyy,MM,dd",
"M d yyyy", "MM dd yyyy",
"d M yyyy", "dd MM yyyy",
"yyyy M d", "yyyy MM dd",
"M/d/yyyy hh:mm:ss tt", "MM/dd/yyyy hh:mm:ss tt",
"d/M/yyyy hh:mm:ss tt", "dd/MM/yyyy hh:mm:ss tt",
"yyyy/M/d hh:mm:ss tt", "yyyy/MM/dd hh:mm:ss tt",
"M-d-yyyy hh:mm:ss tt", "MM-dd-yyyy hh:mm:ss tt",
"d-M-yyyy hh:mm:ss tt", "dd-MM-yyyy hh:mm:ss tt",
"yyyy-M-d hh:mm:ss tt", "yyyy-MM-dd hh:mm:ss tt",
"M.d.yyyy hh:mm:ss tt", "MM.dd.yyyy hh:mm:ss tt",
"d.M.yyyy hh:mm:ss tt", "dd.MM.yyyy hh:mm:ss tt",
"yyyy.M.d hh:mm:ss tt", "yyyy.MM.dd hh:mm:ss tt",
"M,d,yyyy hh:mm:ss tt", "MM,dd,yyyy hh:mm:ss tt",
"d,M,yyyy hh:mm:ss tt", "dd,MM,yyyy hh:mm:ss tt",
"yyyy,M,d hh:mm:ss tt", "yyyy,MM,dd hh:mm:ss tt",
"M d yyyy hh:mm:ss tt", "MM dd yyyy hh:mm:ss tt",
"d M yyyy hh:mm:ss tt", "dd MM yyyy hh:mm:ss tt",
"yyyy M d hh:mm:ss tt", "yyyy MM dd hh:mm:ss tt"
};
DateTime dateValue;
foreach (string dateStringFormat in formats)
{
if (DateTime.TryParseExact(checkDate, dateStringFormat,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dateValue))
//Console.WriteLine("Converted '{0}' to {1}.", dateStringFormat, dateValue.ToString("yyyy-MM-dd"));
return dateStringFormat;
}
return null;
}
我期望的結果
30.03.2016 14:38:20
04.04.2016 11:08:10
結果我得到
01.01.0001 00:00:00
01.01.0001 00:00:00
答案很簡單:不可能,所以請停止嘗試。
證明: 任何格式都包括Mdyyyy
以及dMyyyy
。 在這種情況下,1.2.2016可以代表
結論:不可能進行任何格式的轉換,因為沒有附加信息就無法解析不明確的日期。
注意:這與C#或您選擇的技術無關。 您的要求被打破了。 修復它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.