c# 時(shí)間字符與SqlServer查詢時(shí)間結(jié)果比較
c# 時(shí)間字符與SqlServer查詢時(shí)間結(jié)果比較
有時(shí)我們需要查詢數(shù)據(jù)庫(kù)時(shí)間字段返回結(jié)果中有時(shí)間格式的字符串這個(gè)字符串要與某變量進(jìn)行比較如果相等就進(jìn)行下一步操作,但返回的時(shí)間字符串有時(shí)是“yyyy/MM/dd HH: mm:ss”而我們的變量字符串又是“yyyy-MM-dd HH: mm:ss”這樣一來就無法比較,有必要進(jìn)行時(shí)間格式的轉(zhuǎn)換來達(dá)到目的。
如以下數(shù)據(jù)格式為時(shí)間變量字符串
1 TimeStr = "2021-12-27 15:03:51"; 2 //轉(zhuǎn)換時(shí)間日期格式 3 string compareStr = Convert.ToDateTime(TimeStr).ToString("yyyy - MM - dd HH: mm:ss");
即使時(shí)間字符串是yyyy-MM-dd HH: mm:ss格式也要進(jìn)行轉(zhuǎn)換一次,這樣可以防止多輸入了空格
使字符串長(zhǎng)度發(fā)生變化
數(shù)據(jù)庫(kù)查詢出來的結(jié)果也要進(jìn)行同樣的轉(zhuǎn)換
數(shù)據(jù)庫(kù)查詢結(jié)果在ds中
1 private List<string>GetQueryData(DataSet ds, string ColumnName) 2 { 3 List<string> list = new List<string>(); 4 //列Index 5 int columnInt = 0; 6 if (ds != null && ds.Tables.Count > 0) 7 { 8 //循環(huán)查詢DateSet表中的行數(shù) 9 for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 10 { 11 for (int j = 0; j < ds.Tables[0].Columns.Count; j++) 12 { 13 //查詢扣分時(shí)間段名所在位置 14 if (ColumnName == ds.Tables[0].Columns[j].ColumnName.ToString()) 15 { 16 columnInt = j; 17 } 18 19 } 20 //添加單元格內(nèi)容到集合 21 //轉(zhuǎn)換時(shí)間帶毫秒 22 //string timeToStr = Convert.ToDateTime(ds.Tables[0].Rows[i][columnInt]).ToString("yyyy - MM - dd HH: mm:ss.fff"); 23 //轉(zhuǎn)換時(shí)間格式不帶毫秒 24 string timeToStr = Convert.ToDateTime(ds.Tables[0].Rows[i][columnInt]).ToString("yyyy - MM - dd HH: mm:ss"); 25 26 list.Add(timeToStr.ToString()); 27 } 28 29 } 30 else 31 { 32 list = null; 33 } 34 return list; 35 }
這樣時(shí)間格式就一樣了,即可進(jìn)行比較如果相等就進(jìn)行下一步的操作

浙公網(wǎng)安備 33010602011771號(hào)