比较以dd/mm/yyyy formate表示的两个日期时间 [英] compare two date time in dd/mm/yyyy formate
本文介绍了比较以dd/mm/yyyy formate表示的两个日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个日期,分别是dd/mm/yyyy或dd/MM/yyyy.我想比较两个日期,但是当我使用convert.todatetime()时,它没有给我适当的解决方案.
没有人对此比较有任何了解.
请尽快答复
I have two dates in format of dd/mm/yyyy or dd/MM/yyyy. I want to compare both date but when I am using convert.todatetime(), its not giving me proper solution.
There is any one have any idea about this comparisions.
Please reply soon
推荐答案
一个简单的DateTime.Compare(date1,date2)应该可以工作.
http://msdn.microsoft.com/en-us/library/system.datetime. compare.aspx [^ ]
A simple DateTime.Compare(date1,date2) should work.
http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx[^]
如果使用自定义日期时间格式,则必须使用DateTime.TryParseExact
.
首先,
You have to useDateTime.TryParseExact
if you are using custom date time format.
First,
using System.Globalization;
DateTimeFormatInfo dateFormat = new DateTimeFormatInfo();
dateFormat.DateSeparator = "/";
string input1 = "18/10/2012";
string input2 = "17/10/2012";
DateTime date1 = DateTime.MinValue;
DateTime date2 = DateTime.MinValue;
if (DateTime.TryParseExact(input1, "dd/MM/yyyy", dateFormat, DateTimeStyles.AllowWhiteSpaces, out date1))
{
// Date 1 is a valid date
}
else
{
throw new Exception("Input 1 is not a valid recognised date");
}
if (DateTime.TryParseExact(input2, "dd/MM/yyyy", dateFormat, DateTimeStyles.AllowWhiteSpaces, out date2))
{
// Date 2 is a valid date
}
else
{
throw new Exception("Input 2 is not a valid recognised date");
}
if (date1 > date2)
{
// Do something
}
else
{
// Do something
}
string strFromDate = "26/03/2012";
string strToDate = "26/04/2012";
DateTime FromDate = DateTime.ParseExact(strFromDate, "dd/MM/yyyy",null);
DateTime ToDate = DateTime.ParseExact(strToDate, "dd/MM/yyyy", null);
int result = DateTime.Compare(FromDate, ToDate);
if (result < 0)
{
//from date is less than to date
}
这篇关于比较以dd/mm/yyyy formate表示的两个日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文