使用linq C#的字符串日期比较 [英] string date comparsion using linq C#

查看:370
本文介绍了使用linq C#的字符串日期比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字符串日期比较使用linq C#



我收到错误字符串未被识别为有效日期时间



string date comparsion using linq C#

I got error "String was not recognized as a valid DateTime"

string ctfromdate="20/10/2015";
string cttodate="20/10/2015";

var startDate = DateTime.Parse(ctfromdate);
var EndDate = DateTime.Parse(cttodate);





Linq代码:





Linq code:

   var date = item.ctroomlist.Where(x => x.RoomTypeId == RoomTypeId).SingleOrDefault().ctroomrate.
Where(x => Convert.ToDateTime(x.Date)>=startDate &&Convert.ToDateTime(x.Date)<= EndDate).ToList();

推荐答案

试试这个,

var fromDate = DateTime.ParseExact(ctfromdate,dd / MM / yyyy,null);



-KR
Try this,
var fromDate = DateTime.ParseExact(ctfromdate, "dd/MM/yyyy", null);

-KR


嗯...

简而言之:string表示 DateTime 数据类型取决于本地化。



请参阅:

< a href =https://msdn.microsoft.com/en-us/library/ff647353.aspx> Web客户端的设计和实施指南 [ ^ ]

如何:向Web用户显示本地化日期和时间信息 [ ^ ]

格式化特定文化的日期和时间 [ ^ ]



我建议使用扩展方法使用特定的本地化将字符串转换为DateTime:

Hmmm...
In few words: string representation of DateTime data type depends on localization.

Please see:
Design and Implementation Guidelines for Web Clients[^]
How to: Display Localized Date and Time Information to Web Users[^]
Formatting Date and Time for a Specific Culture[^]

I'd suggest to use extension method to "convert" string into DateTime using specific localization:
public static class DateExtensionMethods
{
	public static DateTime StrToDate(string strDate)
	{	
		System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US"); //en-US //fr-FR //de-DE
		DateTime dt;
		//if convertion failed, return default value 
		return DateTime.TryParse(strDate, culture, System.Globalization.DateTimeStyles.None, out dt) ? dt : new DateTime(1899,12,31);
	}
}





用法:



Usage:

void Main()
{
    List<string> stringDates = new List<string>()
        {"20/10/2015",
        "10/20/2015",
        "2013/10/20",
        "10/20/2014",
        "2015/10/20",
        "2015/20/10"};

    var result = stringDates.Select(d=>DateExtensionMethods.StrToDate(d));

}





结果:



Result:

1899-12-31 00:00:00
2015-10-20 00:00:00
2013-10-20 00:00:00
2014-10-20 00:00:00
2015-10-20 00:00:00
1899-12-31 00:00:00





最后评论:

您应该处理数据,而不是字符串表示!


var date = item.ctroomlist.Where(x => x.RoomTypeId == RoomTypeId).SingleOrDefault().ctroomrate.AsEnumerable().Where(x => DateTime.Parse(x.Date)>



you在你的问题中遗漏了一些代码,但上面应该这样做!


you miss some code in your question but the above should do!


这篇关于使用linq C#的字符串日期比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆