#region 轉換整數方法
/// 將字串日期轉整數
/// 日期字串
/// 整數日期格式
public static int ParseDate(string _date)
{
Console.WriteLine("ParseDate");
//這裡定義所有日期格式
string[] dateFormats = { "dd/MM/yyyy", "yyyy/MM/dd", "yyy/MM/dd", "yy/MM/dd", "y/MM/dd", "yyyy-MM-dd", "yyy-MM-dd", "yy-MM-dd", "y-MM-dd", "yyyy/M/dd", "yyy/M/dd", "yy/M/dd", "y/M/dd", "yyyy-M-dd", "yyy-M-dd", "yy-M-dd", "y-M-dd", "yyyy/MM/d", "yyy/MM/d", "yy/MM/d", "y/MM/d", "yyyy-MM-d", "yyy-MM-d", "yy-MM-d", "y-MM-d", "yyyy/M/d", "yyy/M/d", "yy/M/d", "y/M/d", "yyyy-M-d", "yyy-M-d", "yy-M-d", "y-M-d" };
try
{
//這裡來處理傳入的格式是否為日期格式,只需要簡單一行
DateTime datetime = DateTime.ParseExact(_date, dateFormats, null, DateTimeStyles.AllowWhiteSpaces);
Console.WriteLine("datetime:" + datetime);
int iToken = _date.IndexOf("-", 0);
if (iToken == -1)
iToken = _date.IndexOf("/", 0);
string iYear = _date.Substring(0, iToken);
Console.WriteLine("iYear:" + iYear);
switch (iYear.Length)
{
///這裡是利用datetime.ToString(IFormatProvider)的方法傳出自己想要的統一格式
case 1:
return Int32.Parse(datetime.ToString("yMMdd"));
case 2:
return Int32.Parse(datetime.ToString("yyMMdd"));
case 3:
return Int32.Parse(datetime.ToString("yyyMMdd"));
case 4:
return Int32.Parse(datetime.ToString("yyyyMMdd"));
default:
return Int32.Parse(datetime.ToString("ddMMyyyy"));
}
return 0;
}
catch (Exception ex)
{
Console.WriteLine("ParseDate ex:" + ex.Message);
return 0;
}
}
/// 將字串時間轉換為整數時間
/// 時間字串(HH:mm:ss
/// HHmmss整數格式
public static int ParseTime(string _time)
{
string[] timeFormats = { "HH:mm:ss", "HH:mm:s", "HH:m:ss", "HH:m:s", "H:mm:ss", "H:mm:s", "H:m:ss", "H:m:s" };
try
{
DateTime datetime = DateTime.ParseExact(_time, timeFormats, null, DateTimeStyles.AllowWhiteSpaces);
return Int32.Parse(datetime.ToString("HHmmss"));
}
catch (Exception ex)
{
return 0;
}
}
#endregion
留言列表