目前程式碼
string sDIS_BEGIN_DATE = "10701011100";
string sDIS_END_DATE = "10712251100";
DateTime dDIS_BEGIN_DATE = DateTime.ParseExact(sDIS_BEGIN_DATE, "yyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture);
DateTime dDIS_END_DATE = DateTime.ParseExact(sDIS_END_DATE, "yyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture);
var dis_L = (from t1 in db.xxx
where t1.dDIS_XXX >= dDIS_BEGIN_DATE
&& t1.dDIS_XXX <= dDIS_END_DATE
orderby t1.dDIS_XXX descending
select t1).ToList();
找出來的資料是無,資料庫內資料有3個(想要找到這3個)
字串轉dateTime有甚麼其他的方式嗎?
最後解答:
因字串為民國年,首先轉成西元年字串,再用DateTime.ParseExact 轉成DateTime
先取出字串前三碼,用INT+1911,在組回字串,最後轉型態DateTime以供LINQ查詢使用
解答程式碼
string sDIS_BEGIN_DATE = "10701011100";
string sDIS_END_DATE = "10712251100";
DateTime dDIS_BEGIN_DATE = AYDateTime.GetTwdate(sDIS_BEGIN_DATE,"yyyyMMddHHmm");
DateTime dDIS_END_DATE = AYDateTime.GetTwdate(sDIS_END_DATE, "yyyyMMddHHmm");
dis_L = (from t1 in db.XXX
where t1.dDIS_XXX >= dDIS_BEGIN_DATE
&& t1.dDIS_XXX <= dDIS_END_DATE
orderby t1.dDIS_XXX descending
select t1).ToList();
//把運算公式整合成函數以供日後使用
public static DateTime GetTwdate(string sValue, string sFormat)
{
int iADNum = 1911;
return DateTime.ParseExact((int.Parse(sValue.Substring(0, 3)) + iADNum) + sValue.Substring(3), sFormat, System.Globalization.CultureInfo.InvariantCulture);
}
補充:函數內的參數sFormat可以預設格式,假如你已經固定那些格式,如下
public static DateTime GetTwdate(string sValue)
{
int iADNum = 1911;
string[] sFormat = {
"yyyy/M/d tt hh:mm:ss",
"yyyy/MM/dd tt hh:mm:ss",
"yyyy/MM/dd HH:mm:ss",
"yyyy/M/d HH:mm:ss",
"yyyy/M/d",
"yyyy/MM/dd"
};
return DateTime.ParseExact((int.Parse(sValue.Substring(0, 3)) + iADNum) + sValue.Substring(3), sFormat, System.Globalization.CultureInfo.InvariantCulture);
}