简体   繁体   中英

C# timestamp comparison by string.Compare

Will using string.Compare(timeA,TimeB) always return -1 given that:

timeA is a timestamp that happened before timeB

and

both are in this format: 12/27/2012 00:59:06 aka mm/dd/yyyy hh:mm:ss via DateTime.UtcNow

Well yes. Why would you expect that to work? If you want to sort by time , parse them both into DateTime values and compare those. You're comparing them as strings so they'll be compared lexicographically. Of course if your timestamp format was yyyy-MM-ddTHH:mm:ss or something similar, you could compare them lexicographically - but your current format just isn't designed for sorting.

You could write an IComparer<string> which did the parsing each time, but you'd be much better off just parsing the values as early as you could, and keeping them in their more native representation ( DateTime ) for as long as possible.

You are comparing your Timestamps as a string . Just use < and > with DateTime.Parse()

value timea = DateTime.Parse(timeA);
value timeb = DateTime.Parse(timeB);

if( timeA > timeB )
{
  // your code...
}

For

string.Compare(timeA, timeB) 

to work, timeA and timeB must be strings. And strings are compared alphabetically, so a string beginning with a 1, like '12/27/2012' will always be smaller that a string that begins with a 2, like '2/27/2010' .

In order to compare dates, you could use:

DateTime.Compare(timeA, timeB) 

where timeA and timeB are DateTime 's. If, as you say, they are both generated in your code, just avoid using a .ToString() on them.

String.Compare(string strA, string strB);

Returns: // A 32-bit signed integer that indicates the lexical relationship between the // two comparands.Value Condition Less than zero strA is less than strB. Zero // strA equals strB. Greater than zero strA is greater than strB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM