Date subtraction in C# - c#

My task is to get quantity of Days when I subtract the Current Date from a fixed date.
<script language="C#" runat="server">
System.DateTime thisDay = DateTime.Today;
System.DateTime dateCountFrom = new DateTime(2016, 6, 1, 0, 00, 00);
</script>
So I have 2 dates and everything is working perfectly. But how can I subtract one from the other?
(dateCountFrom-thisDay).totaldayscount;
causes an error, tried other ways - same result.
I succeeded only by doing this:
<%= ((DateTime.Now-(new DateTime(2016,6,1))) *-1).TotalDays %>
But I need to eval result and multiply by -1.
Any ideas how I can do this?

You should use the DateTime.Subtract method, this will return a TimeSpan variable containing the difference in time between the dates
TimeSpan diff = dateCountFrom.Subtract(DateTime.Now);
diff = TimeSpan.FromTicks(diff.Ticks * -1);
Instead of this though, if you want it multiplied by -1, you can just do the opposite sum
TimeSpan diff = DateTime.Now.Subtract(dateCountFrom);

(thisDay - dateCountFrom).TotalDays and (dateCountFrom-thisDay).TotalDays are both perfectly legal and won't result in an error. The only difference is that one result will be negative and the other positive.
If you only need the number of days between the two dates, regardless of which one is later, you can use
int days = Math.Abs((thisDay - dateCountFrom).TotalDays)
If you know, one of the dates will always be later then the other one, (for instance dateCountFrom will always be in the future) use this as minuend (ie the date, which is subtracted from) and the other one as subtrahend (ie the date, that is substracted). Then the number of days will also be always positive.

Related

Add the seconds to date to calculate Time

Quick question, I've got this Program which gives me the seconds past since 01.01.2000.
E.g. the Seconds for 12.02.2016 11:23:55 would roughly be 508590531 seconds.
Is there a Method that given the seconds past and the start date, that calculates the end date?
I am aware that I could calculate the Minutes/Days/Months/Years that passed by hand, and then try to calculate the 'endTime' but I'd have to take care that I don't make a mistake by missing out a leap year for instance.
Quick Definition just to be totally clear:
Start Date : 01.01.2000
End Date: Current Date
Time passed: Seconds passed between start date and end date
It's easy. Just add the seconds, no magic or new solution required.
DateTime AddedFrom2000 = new DateTime(2000, 1, 1).AddSeconds(508590531);
Sure.
You can subtract to each other and use TimeSpan.TotalSeconds property like;
var ts = DateTime.Now - new DateTime(2000, 1, 1);
Console.WriteLine(ts.TotalSeconds);
If you wanna get it as an int, you can explicitly cast it as (int)ts.TotalSeconds.
If you already have seconds and you want to calculate based on your start date, you can use AddSeconds method like;
var dt = new DateTime(2000, 1, 1).AddSeconds(508590531); // {12.02.2016 11:08:51}
var newDate = oldDate.AddSeconds(numSeconds);

How to get a Timespan of 1 year?

I want to get a Timespan structure which represent a year in C#.
The tricky thing is that what a year is, depends on where it starts.
You can do
DateTime now = DateTime.Now;
TimeSpan span = now.AddYears(1) - now;
This would give you the 1 year timespan from the current moment to one year later
The key question here is: which year?
The length of the timespan obviously depends on whether the year you want is a leap year or not and when it starts.
If you want one year starting from today go with #sehe's answer.
If you want the current year go with #Oyvind,
If you want a reasonable approximation you can go with #Nayan, or for a 365.25 approximation use:
TimeSpan oneYearSpan = new TimeSpan(365, 6, 0, 0);
You can't, as a year doesn't have a fixed length (is it 365 or 366 days or about 365.25?). That's also why you can't have a month as TimeSpan (28, 29, 30, 31 days??)
Rough example:
TimeSpan oneYearSpan = new TimeSpan(365, 0, 0, 0);
Will this do?
DateTime intialDate = Date.Now.Date;
TimeSpan yearSpan = intialDate.AddYears(1).Subtract(intialDate)
As other peoplehave mentioned you may want to consider leap years. In that case you can intiate intialDate accordingly.
If you want to be pretty accurate you could use the number of nano seconds in a year.
I think that this moves by 0.5 seconds every century, so should be good for a long while yet!
public TimeSpan MyYear
{
get
{
// Year = 3.1556926 × 10^16 nanoseconds
return new TimeSpan(31556926000000000);
}
}
There are already some good answers on this page, this is just another option.
It depends on which year you want to represent, since not all years are of equal length.
This is the way to find the length of 2010 for example:
var timestamp = new DateTime(2011, 1, 1) - new DateTime(2010, 1, 1);
Change the year in the DateTimes to find the length of the year you want.
Here's how to do this, utilizing the IsLeapYear to determain number of day.
int span = DateTime.IsLeapYear(1996) ? 366: 365;
var year1996 = new TimeSpan(span, 0, 0, 0);

ASP.NET: Get milliseconds since 1/1/1970

I have an ASP.NET, VB.NET Date, and I'm trying to get the number of milliseconds since January 1st, 1970. I tried looking for a method in MSDN, but I couldn't find anything. Does anyone know how to do this?
Starting with .NET 4.6, The method ToUnixTimeMilliseconds provides a more accurate solution.
From DateTimeOffset:
DateTimeOffset.Now.ToUnixTimeMilliseconds()
From DateTime:
new DateTimeOffset(dateTime).ToUnixTimeMilliseconds()
Source: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimemilliseconds?view=netframework-4.6#System_DateTimeOffset_ToUnixTimeMilliseconds
You can subtract any two DateTime instances and get TimeSpan and TotalMilliseconds would give you total milliseconds. Sample below.
DateTime dt1970 = new DateTime(1970, 1, 1);
DateTime current = DateTime.Now;//DateTime.UtcNow for unix timestamp
TimeSpan span = current - dt1970;
Console.WriteLine(span.TotalMilliseconds.ToString());
one liner
//DateTime.MinValue is 01/01/01 00:00 so add 1969 years. to get 1/1/1970
DateTime.Now.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds;
Alternatively, you can use the Ticks property and avoid construction of a temporary object:
long epochTime = (DateTime.UtcNow.Ticks - 621355968000000000) / 10000;
However, this isn't entirely
Reasoning:
DateTime d = new DateTime(1970, 01, 01);
var temp = d.Ticks; // == 621355968000000000
This will provide the UNIX Epoch in milliseconds.
(Respects UTC time instead of your local time)
Split(DateTime.UtcNow.Subtract(DateTime.MinValue.AddYears(1969)).TotalMilliseconds(), ".", 2)(0)

C# Number of days between two dates problem

I have a small problem with the code below, the 'days' variable always seems to be 0 no matter how far apart the days are.
Can you see anything obviously wrong?
System.TimeSpan span = dates[0] - dates[1]; // e.g. 12/04/2010 11:44:08 and 18/05/2010 11:52:19
int days = (int)span.TotalDays;
if (days > 10) //days always seems to be 0
{
throw new Exception("Over 10 days");
}
Thanks
As you are subtracting the later date from the earlier date, according to your comments, TotalDays will be negative. In your example, -36.
Therefore a comparison of (days > 10) will fail. You should use
int days = Math.Abs((int)span.TotalDays);
Assuming you haven't set date[0] equal to date[1], there is no reason why TotalDays will be returning zero for the sample dates you have in your comments.
The total days should be negative but in any case not zero, cause you substract the earlier date from the later date. It seems dates[0] and dates[1] are not containing what you think.
I just tested this:
DateTime date1 = new DateTime(2010, 12, 31);
DateTime date2 = new DateTime(2010, 1, 1);
TimeSpan timeSpan = date2 - date1;
Console.WriteLine(timeSpan.TotalDays);
This program produces the output: -364. So it should perfectly work!
One question: Did you use DateTime[] for the dates-array?
BTW: days > 10 does not check if days is zero.
If we assume your code looks exactly like that, and the dates array is correctly populated, then there is nothing wrong here that would cause days to be exactly zero. Maybe check that your dates array has the correct values in it? Barring that, post more code?
Either do this:
System.TimeSpan span = dates[0] - dates[1];
int days = Math.Abs((int)span.TotalDays);
if (days > 10)
{
throw new Exception("Over 10 days");
}
Or this:
System.TimeSpan span = dates[1] - dates[0];
int days = (int)span.TotalDays;
if (days > 10)
{
throw new Exception("Over 10 days");
}

subtract 2 datetime fields to get the days left difference

Would appreciate it if anyone can help me figure out to substract 2 datetime fields to get the days left difference.
This is very easy to do with C#. For comparing DateTimes, we have a class called TimeSpan. The TimeSpan structure, in this case, would be defined as the difference between your two datetimes.
Let's say that your DateTimes are called start and end.
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
We have established our DateTimes to June 14, 2009 and December 14, 2009.
Now, let's find the difference between the two. To do this, we create a TimeSpan:
TimeSpan difference = end - start;
With this TimeSpan object, you can express the difference in times in many different ways. However, you specifically asked for the difference in days, so here's how you can get that:
Console.WriteLine("Difference in days: " + difference.Days);
Thus, the property is called TimeSpan.Days.
Final Code
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
Console.WriteLine("Difference in days: " + difference.Days); //Extract days, write to Console.
For more information on using the TimeSpan structure, see this MSDN documentation (especially the C# examples).
Hope I helped!
UPDATE: Some answers have suggested taking doing subtraction in one step, such as with:
int days = (dt2 - dt1).Days;
or
int numDaysDiff = Math.Abs(date2.Subtract(date1).Days);
However, they are the same thing as in my answer, only shortened. This is because the DateTime.Subtract() method and the subtraction operator of DateTimes returns a TimeSpan, from which you can then access the amount of days. I have specifically used the longer approach in my code sample so that you clearly understand what is going on between your DateTime and TimeSpan objects and how it all works. Of course, the other approaches I just mentioned are fine, too.
UPDATE #2:
A very similar question was asked before, and it can be found here. However, the main point of that question was why the code sample (which is essentially equivalent to that of all the answers) sometimes provides an answer which is a day off. I think this is also important to this question.
As the main answer to the other question suggests, you can use this code:
int days = (int)Math.Ceiling(difference.TotalDays);
This code uses Math.Ceiling, which, according to MSDN, is:
Returns the smallest integral value
that is greater than or equal to the
specified double-precision
floating-point number.
How Do You Want to Count the Days?
Thus, we now have an issue with how you want to count the days. Do you want to count part of a day (such as .5 of a day) as:
A full day - this would use Math.Ceiling to round up TimeSpan.TotalDays, so that you're counting started days.
Part of a day - you can just return the TimeSpan.TotalDays (not rounded) as a decimal (in the double datatype)
Nothing - you can ignore that part of a day and just return the TimeSpan.Days.
Here are code samples for the above:
Counting as a full day (using Math.Ceiling() to round up):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
int days = (int)Math.Ceiling(difference.TotalDays); //Extract days, counting parts of a day as a full day (rounding up).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Counting as part of a day (NOT using Math.Ceiling(), instead leaving in decimal form as a part of a day):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
double days = difference.TotalDays; //Extract days, counting parts of a day as a part of a day (leaving in decimal form).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Counting as nothing of a day (rounding down to the number of full days):
//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);
TimeSpan difference = end - start; //create TimeSpan object
int days = difference.TotalDays; //Extract days, counting parts of a day as nothing (rounding down).
Console.WriteLine("Difference in days: " + days); //Write to Console.
Use
TimeSpan
DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
TimeSpan travelTime = arrival - departure;
The easiest way out is, making use of TimeSpan().
This Subtract function will return you the difference between two dates in terms of time span. Now you can fetch fields like days, months etc. To access days you can make use of
Here is the sample code;
VB.Net code;
Dim tsTimeSpan As TimeSpan
Dim ldDate1 as Date
Dim ldDate2 as Date
'Initialize date variables here
tsTimeSpan = ldDate1 .Subtract(ldDate2)
Dim NumberOfDays as integer = tsTimeSpan.days
C#.Net code;
DateTime lDate1;
DateTime lDate2;
TimeSpan tsTimeSpan ;
int NumberOfDays;
//Initialize date variables here
tsTimeSpan = ldDate1 .Subtract(ldDate2);
NumberOfDays = tsTimeSpan.days;
DateTime dt1 = new DateTime(2009,01,01,00,00,00);
DateTime dt2 = new DateTime(2009,12,31,23,59,59);
int days = (dt2 - dt1).Days;
Number of Days Difference
These answers take the number of days as an int from the System.TimeSpan structure that is the result of subtracting two System.DateTime fields...
Quick answer - gets the number of days difference.
int numDaysDiff = date2.Subtract(date1).Days;
Alternate answer - uses Math.Abs to ensure it's not a negative number, just in case the dates might be supplied in either order.
int numDaysDiff = Math.Abs( date2.Subtract(date1).Days );
Some sample data to finish it off using System namespace:
// sample data
DateTime date1 = DateTime.Now;
DateTime date2 = DateTime.Now.AddDays(10);
MSDN References (and more sample code ):
System.TimeSpan structure
System.DateTime structure
System.Math.Abs(..) method
DateTime theDate = DateTime.Today;
int datediff = theDate.Subtract(expiryDate).Negate().Days;
if expiryDate > theDate then you get Negative value: -14
expiryDate is less than theDate then you get positive value: 14
You May obviously want this in a scenario such as
Send a Notification Email 14days before expiry
Send another notification Email 14 days after expiry
You need a difference that could be negative value
You should look at TimeSpan.
To get the exact days ignoring the time section
DateTime d1 = Convert.ToDateTime(DateTime.Now.ToShortDateString());
DateTime d2 = Convert.ToDateTime(DateTime.Now.AddDays(46).ToShortDateString());
var days = Convert.ToInt32(d2.Subtract(d1).TotalDays)

Categories

Resources