How to find the positive difference between two DateTime in C# - c#

I've two DateTime variable regardless of which is greater than the other in time.
Datetime date1, date2;
How should I find the positive difference of both on "days" basis?
(date1-date2) might give positive/negative result but I also need the no: of days difference.
Assume both are on the same TimeZone

double days = Math.Abs((date1-date2).TotalDays);

If you want an (unsigned) integer value:
Math.Abs(date1.Subtract(date2).Days)
If you want an (unsigned) double value:
Math.Abs(date1.Subtract(date2).TotalDays)

Just use the Days property on the timespan (which is the resulting type from date1 - date2). It returns a signed int.

You could try:
Math.Abs((dateA - dateB).Days);
or if you want the result to be fractional:
Math.Abs((dateA - dateB).TotalDays);

Related

How to convert a string formatted like 2018-12-27T02:23:29 to Unix Timestamp in C#

I'm assuming I should just parse the string into a DateTime and go from there... But is there a better way of doing this?
You can use the DateTimeOffset struct, which has a ToUnixTimeSeconds (or ToUnixTimeMilliseconds) method you can use:
long unixTimestamp = DateTimeOffset.Parse("2018-12-27T02:23:29").ToUnixTimeSeconds();
If you're curious how it's done, the source is here: https://referencesource.microsoft.com/#mscorlib/system/datetimeoffset.cs,8e1e87bf153c720e
You should parse it to a normal DateTime object using something from the DateTime.Parse/ParseExact family of functions, and then call a method like this:
public int ToUnixTime(DateTime d)
{
var epoch = new DateTime(1970,1,1);
return (int)(d - epoch).TotalSeconds;
}
DateTime interally stores the "Ticks" (a invented Time unit) since "12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001), in the Gregorian calendar". As a Int64/Long Number. DateTime thus beats UnixTime easily in possible values. Converting to DateTime should be lossless.
Any ToString() call, any other Property call will simply calculate the values based on those Ticks (and culture/Timezone settings for ToString()). Everything else is just a interpretation of the Tick value.
You should parse to DateTime. And getting from Ticks to something as inprecise as the UnixTime is easy math. See Joels Answer for that.
Do note however the DateTimes preccision and accuaracy do not match fully: https://blogs.msdn.microsoft.com/ericlippert/2010/04/08/precision-and-accuracy-of-datetime/ DateTime.Now will usually give you only return values in 18 ms steps. And even the Stopwatch has issues with values < 1 ms.

Convert Zero Datetime vs Allow Zero Datetime

Convert Zero Datetime=true returns DateTime.MinValue while Allow Zero Datetime return MySqlDateTime.
What else differentiate these 2 settings ?
When to use which one?
Can they be used interchangeable ?
What is pro and cons of them ?
You can refer to this point for a little clarification: http://forums.devart.com/viewtopic.php?t=21367
But it all boils down to how you want to handle zero values on DateTime, When you use Allow Zero DateTime it cannot be converted to a DateTime because it doesn't support zero value. If you use Convert Zero DateTime it will use DateTime but it will return the lower value possible for date which is DateTime.MinValue.

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.

Date Conversion from value in C#

Does anyone possibly recognize the following value "40195.315752" as a date? I need to convert/format this value-based date to a System.DateTime object, but don't understand it's format.
Thanks.
It's a serial date-time, which means it's the number of days since a particular date. Note that you need to know the date which it is an offset to. In Excel, that would be Jan 1st, 1900, which makes your date 17/01/2010 07:34:41, but other programs will vary.
Another common start date is 1st January 1970 (Unix Epoch).
enjoy it:
DateTime.FromOADate(40195.315752).ToLongDateString()
and to convert it to DateTime
DateTime MyDateTime = DateTime.FromOADate(40195.315752);
It means Sunday,January 17 2010
That would possibly be the number of days since a certain date (possibly january 1st 1900), before the decimal point?
the value you have displayed is a double...
var val = 40195.315752;
var span = System.TimeSpan.FromMilliseconds(val);
var time = new DateTime(span.Ticks);
above will convert it to Datetime but besure to note that System.Timespan continas several overloads to load span you need to identify which one is that you want...

Calculating past datetime in C#

I am working on an algorithm in C# to calculate a past DateTime based on an input string with the following characteristics:
The string contains an integer followed by either 'D', 'M' or 'Y', such as "1D" or "90M".
The output will be DateTime.Now minus the corresponding number of days, months or years.
The issue I am having is that if, for instance, I switch the input string on a Regex (D, M or Y) and subtract the corresponding TimeSpan from DateTime.Now, the new TimeSpan() constructor does not accept months or years, only days.
if (new Regex(#"[0-9]+D").IsMatch(value))
{
newDate = DateTime.Now - TimeSpan(Int32.Parse(value.Replace("D", "")), 0, 0);
}
This logic is fine if the input string is in days, but the constructor for TimeSpan does not accept months or years, and it would be incredibly inaccurate if I assumed each month had 30 days, or each year had 365 days.
Does anyone have thoughts on how to implement this algorithm?
Thanks!
DateTime has AddMonths, AddDays and AddYears methods. Use them with minus to substract
Could you not rather try using the AddDays/AddMonths/AddYears but with negative numbers?
From DateTime.AddDays Method
The value parameter can be negative or
positive.
And then maybe just implement a switch stament to apply the appropriate Add method.
To subtract months, I create a new DateTime and just evaluate month/year. So 1/2010 - 6 months would be 6/2010... once you have the month/year established, you can look at the original datetime day component, and ensure it fits within the month.
That's what I did. Year was evaluated the same way. Subtracting days is easy; use the TimeSpan component to do it.
Remember that you can add negative amounts as well and check out this method and this one.
http://msdn.microsoft.com/en-us/library/3z48198e.aspx
TimeSpan.TryParse accepts very close to your string as long as you can fits its formatting OR convert from yours to its.

Categories

Resources