Rolando F Rolando F - 1 year ago 82
C# Question

Comparing timestamps in C#

I'm rewriting some code from Java to C#. Unfortunately most of code was "hacked" so I'm just guessing how the code was written. Right now, I have to reproduce some inserts into data base..

I got a little confused in the time stamp I have to insert. For example in current database the record is:

10-AUG-10 PM

Values in current database

In my code I was able to get something similar:
22-Aug-16 AM

The idea of this code is to compare the timestamp created with the current one and perform some actions if the first one was created within the last 60 seconds.

First question:

How can I exactly reproduce
, I see that all the records have "000" at the end, do I need an if/else for that or is there any function to keep the last part 9 digits long?

Second question:

If it was only numbers, I know I can retrieve the values from the database and then compare, but since the format is:
, not really sure how to handle that part

Any suggestions?


After reading some comments I got a better understanding on what to do with this issue. I decided to keep things simple and just create DateTime variables and then just use a subtract method in order to see how many minutes of difference there are between those two.


DateTime guidTimestamp; //8/25/2016 10:02:47 AM

DateTime currentTimestamp = DateTime.Now;

public int calculateMinutes(DateTime dt1, DateTime dt2)
int min = 0;
min = (int)((dt1 - dt2).TotalSeconds);
catch (Exception ex)
Debug.WriteLine("Exception - Date Time error: " + ex.Message);
return min;

Answer Source

The data type of the field in DB is likely string. You shoudn't carry about such a big precision of the value as MSDN says.

The following line of code produces string with current date in exactly the same format as you mentioned:

DateTime.Now.ToString("dd-MMM-yy tt", System.Globalization.CultureInfo.InvariantCulture).ToUpper() + "000"

The following line of code produces DateTime from your string with custom format:

DateTime.ParseExact("10-AUG-10 AM", "dd-MMM-yy tt", System.Globalization.CultureInfo.InvariantCulture)

As you see you need to get rid of those 3 zeros in the milliseconds part to make ParseExact process the string value. You can read about regular expressions or hardcode it if you wish.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download