开发者

Compare dates as strings

I can't find a way to find all the dates(strings) less then at least one year from now.

i keep in database Date Field strings like "DateTime.toShortDateString()" and i need to compare now.

it looks like month/day/year = 9/6/2011

its need to be lower at least one year from DateTime.now.

i did this and it doesnt return all dates needed just few.

        DateTime Date = DateTime.Now;
        int Year = Date.Year;
        Year -= 1;
        int Month = Date.Month;
        string MonthYear = Month.ToString() + "开发者_运维问答%" + Year.ToString();
        string Query = "SELECT * FROM Orders WHERE DateOrder < @STU ";

           SqlCommand cmd = new SqlCommand(Query, con);
                cmd.Parameters.AddWithValue("@STU", MonthYear);

This is my problem


Modify your database schema and store dates as char(10) in ISO 8601 format (yyyy-mm-dd) or the ISO 8601 compact form (yyyymmdd).

  • http://www.cl.cam.ac.uk/~mgk25/iso-time.html
  • http://en.wikipedia.org/wiki/ISO_8601

That gives you proper collation and proper comparison. Further...DateTime.Parse() and TryParse() will both accept that format regardless of culture (well..one exception: Saudi Arabia, ar-SA. Go figure). DateTime.ToString("Y") orstring.Format( "{0:Y}" , someDateTimeInstance )` will give you the ISO 8601 format.

Should be a simple update to your database.

Even better, if you're using SQL Server 2008: store dates using the new datatype Date.


Maybe deserialize these DateTime strings and then compare as DateTime objects?

var date=DateTime.Parse(stringFromDb, new CultureInfo("en-US"));

Then you can do:

if (dateToCompare1 < dateToCompare2)

Or whatever comparison operator you want.

Edit: from your comment, I think you would like use only dates that are later (or equal to?) one year from now. And so you would do:

var date=DateTime.Parse(stringFromDb, new CultureInfo("en-US"));
if (date >= DateTime.Now.AddYears(1) {
   // Do whatever you want with the "kept" dates
}


Assuming you have a string:

string strDate1 = "09/06/2011";
string strDate2 = "09/06/2011";

DateTime date1 = DateTime.Parse(strDate1);
DateTime date2 = DateTime.Parse(strDate2);

Then compare them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜