2011-04-25 99 views
1

我的问题是,我想从DateTime列表中找到最高DateTime?从DateTime的列表中查找最高日期时间

我有一个数组想string[] btime = new string[100];

在这阵,我存储从该SQL-Server发出日期 SQL查询是[CONVERT(varchar(10),GETDATE(),101)]它返回在MM/DD/YYYY格式的日期
然后我用我自己给出的时间连接日期
.btime[j] = SqlServerDate + " " + 15:20;等等;

现在,从这个定Array我想找到最高的日期和时间

所以,我用这个逻辑

string large="" 
large=btime[0]; 

for (int i = 0; i < j; i++) 
{ 
    if (DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0) 
    { 
     large = btime[i]; 
    } 
} 

但我得到的错误在

if(DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0) 

错误是字符串未被识别为有效日期时间发生此错误是因为我的系统日期时间格式为YYYY/DD/MM

所以PLZ任何一个可以帮助我解决这个问题 我不想改变系统

+0

的ISO8601日期格式的优势了很好的示范。 – pavium 2011-04-25 09:05:51

+0

你有没有试过Convert.ToDateTime()? – SRKX 2011-04-25 09:13:28

+0

你几点加入日期?它必须是'DateTime.Parse'函数有效的有效时间格式。您可以显示数组的内容,在添加SQL Server时间之后以哪种格式构建日期? – 2011-04-25 09:11:34

回答

3

坎格式,

// Containing your datetime field 
string[] btime = new string[100]; 

var max = btime.Select(s => DateTime.Parse(s, "MM/dd/yyyy", CultureInfo.InvariantCulture)).Max(); 
+0

var max = dates.Select(s => DateTime.ParseExact(s,“dd/MM/yyyy”,System.Globalization.CultureInfo.InvariantCulture))。Max();这对我有用!谢谢。 – Singaravelan 2015-09-25 09:10:53

0

使用DateTime.ParseExact方法。 例子:

CultureProvider provider = CultureInfo.InvariantCulture; 
DateTime.ParseExact(btime[i], "yyyy/dd/MM", provider); 
0

你,可以使用DateTime.ParseExact()功能来做到这一点。请参阅以下代码部分。

CurDate = DateTime.ParseExact(Name3, "yyyyMMddhhmmssffff", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None) 
6

其他人提出了解析DateTime的不同方法。这对我来说似乎毫无意义 - 如果您可以更改查询,只需避免首先执行到字符串的转换。您使用的转换次数越少,您遇到这种问题的可能性就越小。

更改查询,以便你最终DateTime值,然后找到最新的一个是微不足道的LINQ:

DateTime latest = dateTimes.Max(); 
0

可以使用DateTime.ParseExact() method

CultureProvider provider = CultureInfo.InvariantCulture; 
DateTime.ParseExact(btime[i], "MM/dd/yyyy HH:mm", provider); 

第二个参数是格式字符串。这指定了你的日期将如何格式化。

由于您在最后加入24小时的时间,您需要HH:mm(HH表示预计会有24小时的时间)。

+1

乔恩Skeet的答案是最好的,但我离开这个,因为它涵盖了24小时的时间被添加到日期。 – 2011-04-25 09:22:43

0

感谢大家。

我有某种答案:

string large = ""; 
large = btime[0]; 
IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture; 

// This Code will convert the System Format in Thread, Not the Actual Format 
// of The System 
CultureInfo ciNewFormat = new CultureInfo(CultureInfo.CurrentCulture.ToString()); 
ciNewFormat.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy"; 
System.Threading.Thread.CurrentThread.CurrentCulture = ciNewFormat; 

for (int i = 0; i < TimeBackupCounter; i++) 
{ 
    if (DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0) 
    { 
     large = btime[i]; 
    } 
} 
相关问题