Milliseconds to the highest possible time value before reaching 0,xx - c#

I would like to write a converter from milliseconds to the highest possible time value before reaching a 0,x value.
Let me clarify this with examples.
Let's assume you have 1500ms this should result in 1,5secs, because its the highest possible digit value not resulting in 0,x.
So different examples would be
10ms = 10,0ms
100ms = 100,0ms
1000ms = 1,0sec
10000ms = 10,0sec
100000ms = 1,6min
1000000ms = 16,0min
10000000ms = 2,7hours
(The method should more or less be endless, so from hours to days, to weeks, to months, to years, to decades and so on...)
Is there a .net method for this?

Something like the following
public static string ConversionMethod(UInt64 ms)
{
// change output format as needed
string format = "######.###";
var cutoffs = new List<UInt64>() {
1000, // second
60000, // minute
3600000, // hour
86400000, // day
604800000, // week = day * 7
2592000000, // month = day * 30
31536000000, // year = day * 365
315360000000, // decade = year * 10
3153600000000, // century = decade * 10 (100 years)
31536000000000, // millenia = century * 10 (1000 years)
31536000000000000 // megayear = year * 100000
// 18446744073709551615 // UInt64 MaxValue
// 31536000000000000000 // gigayear = year * 100000000
};
var postfix = new List<String>() {
"second",
"minute",
"hour",
"day",
"week",
"month",
"year",
"decade",
"century",
"millenia",
"megayear"
};
// The above are listed from smallest to largest for easy reading,
// but the comparisons need to be made from largest to
// smallest (in the loop below)
cutoffs.Reverse();
postfix.Reverse();
int count = 0;
foreach (var cutoff in cutoffs)
{
if (ms > cutoff)
{
return ((decimal)((decimal)ms / (decimal)cutoff)).ToString(format) + " " + postfix[count];
}
count++;
}
return ms + " ms";
}
Conversion for the fraction is a bit dirty, might want to clean that up. Also, you'll have to decide how you want to handle leap years (and leap seconds), etc.

While not the final solution, maybe TimeSpan can help you achieve what you are looking for.
It is to be noted however, TimeSpan supports only up to TotalDays.
var timespan = TimeSpan.FromMilliseconds(1500);
var seconds = timespan.TotalSeconds; // equals: 1.5

It seems the TimeSpan class is the closest thing that meets your need, but clearly it's not exactly what you want. My take on it would look something like this:
public static string ScientificNotationTimespan(int milliseconds)
{
var timeSpan = new TimeSpan(0, 0, 0, 0, milliseconds);
var totalDays = timeSpan.TotalDays;
if (totalDays < 7)
{
if (timeSpan.TotalDays > 1) return timeSpan.TotalDays.ToString() + " days";
if (timeSpan.TotalHours > 1) return timeSpan.TotalHours.ToString() + " hours";
if (timeSpan.TotalMinutes > 1) return timeSpan.TotalMinutes.ToString() + " minutes";
if (timeSpan.TotalSeconds > 1) return timeSpan.TotalSeconds.ToString() + " seconds";
return milliseconds.ToString() + "milliseconds";
}
var weeks = totalDays / 7;
//How long is a month? 28, 29, 30 or 31 days?
var years = totalDays / 365;
if (years < 1) return weeks.ToString() + " weeks";
var decades = years / 10;
if (decades < 1) return years.ToString() + " years";
var centuries = decades / 10;
if (centuries < 1) return decades.ToString() + " decades";
var millenia = centuries / 10;
if (millenia < 1) return centuries.ToString() + " centuries";
return millenia.ToString() + " millenia";
}

Here is solution for years, months using DateTime and Gregorian calendar (meaning leap years, calendar months). Then it uses the TimeSpan solution as already submitted.
static string ToMostNonZeroTime(long ms) {
const int hundretsNanosecondsInMillisecond = 10000;
long ticks = (long)ms * hundretsNanosecondsInMillisecond;
var dt = new DateTime(ticks);
if((dt.Year - 1) > 0) { // starts with 1
double daysToYear = (dt.DayOfYear - 1) * 1.0 / (DateTime.IsLeapYear(dt.Year) ? 366 : 365);
daysToYear += dt.Year - 1;
return $"{daysToYear:0.0} years";
}
if((dt.Month - 1) > 0) {
double daysToMonth = (dt.Day - 1) * 1.0 / DateTime.DaysInMonth(dt.Year, dt.Month);
daysToMonth += dt.Day - 1;
return $"{daysToMonth:0.0} months";
}
// can use TimeSpan then:
var ts = TimeSpan.FromMilliseconds(ms);
if(ts.TotalDays >= 1)
return $"{ts.TotalDays:0.0} days";
if(ts.TotalHours >= 1)
return $"{ts.TotalHours:0.0} hours";
if(ts.TotalMinutes >= 1)
return $"{ts.TotalMinutes:0.0} minutes";
if(ts.TotalSeconds >= 1)
return $"{ts.TotalSeconds:0.0} seconds";
return $"{ms} milliseconds";
}
It prints
100ms: 100 milliseconds
1000ms: 1.0 seconds
10000ms: 10.0 seconds
100000ms: 1.7 minutes
1000000ms: 16.7 minutes
10000000ms: 2.8 hours
100000000ms: 1.2 days
1000000000ms: 11.6 days
20000000000ms: 19.6 months
200000000000ms: 6.3 years
Have a look at https://ideone.com/QZHOM4

Related

Conversion of TimeSpan to a new variable on HHH: mm

I am downloading the list of times from the database
var listaNadgodzinZPoprzMies = _ecpContext.Karta.Where(x => x.Login == userName && x.Rok == numerRoku && x.Miesiac < numerMiesiaca)
.Select(b => string.IsNullOrEmpty(b.SaldoNadgodzin) ? TimeSpan.Zero : TimeSpan.Parse(b.SaldoNadgodzin))
.ToList();
Adds all times
var sumaListaNadgodzinZPoprzMies = listaNadgodzinZPoprzMies.Aggregate(TimeSpan.Zero, (t1, t2) => t1 + t2);
And, I need to convert the number of minutes/ from the variable shown in the image (TimeSpan)
to string to format HHH:mm to other new variable
I scraped out these two functions some time ago in javascript ( I don't know how to convert them to c # ) (I don't know if it will work and whether it will be useful)
function msToTime(duration) {
const minutes = Math.floor((duration / (1000 * 60)) % 60), // 3.4 - 3, 3.5 - 3, 3.8 - 3
hours = Math.floor(duration / (1000 * 60 * 60));
return twoOrMoreDigits(hours) + ":" + twoOrMoreDigits(minutes);
}
function twoOrMoreDigits(n) {
return n < 10 ? '0' + n : n; // if (n < 10) { return '0' + n;} else return n;
}
anyone have any idea?
Here is an example:
TimeSpan time = new TimeSpan(200,1,23);
string strTime = $"{((int)time.TotalHours).ToString("D3")}:{time.Minutes.ToString("D2")}";
Console.WriteLine(strTime);
Output:
200:01
You want to format a timespan, you can achieve it by using this code:
var timespan = TimeSpan.FromMinutes(3180);
var result = timespan.ToString("hh:mm");
Console.WriteLine(result);
hh - hour in 24h format with leading zero
mm - minutes with leading zero
You can read more about timespan formatting here:
https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-timespan-format-strings

Return Months & days from TimeSpan asp.net

I want to return in Seconds, Minuites, Hours, Days, Months et Years from Datetime created.
I wrote this snippet of code
public static string ReturnCreatedSince(DateTime createdOn)
{
//Get current datetime
var today = DateTime.Now;
// Get days in current month
var daysInMonth = DateTime.DaysInMonth(today.Year, today.Month);
double seconds = 60;
double minutes = seconds * 60;
double hours = minutes * 60;
double days = hours * 24;
//double weeks = days * 7;
double months = days * daysInMonth;
double years = months * 12;
//Convert created datetime to seconds
var datetimeInSeconds = (today - createdOn).TotalSeconds;
var createdSince = string.Empty;
if (datetimeInSeconds <= seconds) //seconds between 1 to 60
{
return TimeSpan.FromSeconds(datetimeInSeconds).Seconds.ToString() + " sec";
}
else if (datetimeInSeconds <= minutes)// Minuites between 1 to 60
{
return TimeSpan.FromSeconds(datetimeInSeconds).Minutes.ToString() + " mins";
}
else if (datetimeInSeconds <= hours)// Hours between 1 to 24
{
return TimeSpan.FromSeconds(datetimeInSeconds).Hours.ToString() + " hrs";
}
else if (datetimeInSeconds <= days)// Days between 1 to 24
{
return TimeSpan.FromSeconds(datetimeInSeconds).Days.ToString() + " jrs";
}
else if (datetimeInSeconds <= months)// Months between 1 to 24
{
return (datetimeInSeconds / months).ToString() + " m";
}
else if (datetimeInSeconds <= years)// Years between 1 to 12
{
return (datetimeInSeconds / years).ToString() + " yrs";
}
else
{
return createdOn.ToShortDateString();
}
}
I tested the code with the following values
Edited
For a given datetime
if the number of second is less than 60 then it should return the value in second.
if the number of second is less greater 60 and less than (60 * 60) secs then it should return the value in mins , the same apply for hours, days months and years
Now i have this date "createdOn": "2017-10-16T14:41:16.557" and return 41 days instead of 1 month expected.
how can i fix it
#Tarik solution for months will get you the total number of months between the startDate and endDate.
To get the last remaining months, include this while loop statement.
DateTime startDate = new DateTime(2003, 1, 1);
DateTime endDate = new DateTime(2007, 12, 1);
int nbYears = endDate.Year - startDate.Year;
int nbMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
while (nbMonths > 12)
{
nbMonths = nbMonths % 12;
}
Console.WriteLine($"{nbYears} year(s) and {nbMonths} month(s)");
Without the while loop, it prints: 4 year(s) and 59 month(s)
With the while loop, it prints: 4 year(s) and 11 month(s)
It might be easier to use embedded methods :
DateTime startDate = new DateTime(1970, 01, 01);
DateTime endDate = DateTime.Now.ToUniversalTime();
TimeSpan diff = (endDate - startDate);
Console.WriteLine("Number of seconds:" + diff.TotalSeconds);
Console.WriteLine("Number of minutes:" + diff.TotalDays);
Console.WriteLine("Number of hours:" + diff.TotalHours );
Console.WriteLine("Number of days:" + diff.TotalDays);
//months
int nbMonths = ((endDate.Year - startDate.Year) * 12) + endDate.Month - startDate.Month;
Console.WriteLine("Number of months:" + nbMonths);
//years
int nbYears = endDate.Year - startDate.Year;
Console.WriteLine("Number of years:" + nbYears);
Console.ReadKey();

How to calculate remaining minutes to "next" half an hour or hour?

I would like to calculate the remaining minutes to the "next" half an hour or hour.
Say i get a start time string of 07:15, i want it to calculate the remaining minutes to the nearest half an hour (07:30).
That would be 15min.
Then i can also have an instance where the start time can be 07:45 and i want it to calculate the remaining minutes to the nearest hour (08:00).
That would also be 15min.
So any string less then 30min in a hour would calculate to the nearest half an hour (..:30) and any string over 30min would calculate to the nearest hour (..:00).
I don't want to do a bunch of if statements, because i get from time strings that can start from and minute in an hour.
This is what i do not want to do:
if (int.Parse(fromTimeString.Right(2)) < 30)
{
//Do Calculation
}
else
{
//Do Calculation
}
public static string Right(this String stringValue, int noOfCharacters)
{
string result = null;
if (stringValue.Length >= noOfCharacters)
{
result = stringValue.Substring(stringValue.Length - noOfCharacters, noOfCharacters);
}
else
{
result = "";
}
return result;
}
Is there not an easier way with linq or with the DateTime class
Use modulo operator % with 30. Your result will be equal to (60 - currentMinutes) % 30. About LINQ its used for collections so i can't realy see how it can be used in your case.
You can use this DateTime tick-round approach to get the timespan until next half hour:
var minutes = 30;
var now = DateTime.Now;
var ticksMin = TimeSpan.FromMinutes(minutes).Ticks;
DateTime rounded = new DateTime(((now.Ticks + (ticksMin/2)) / ticksMin) * ticksMin);
var diff=rounded-now;
var minUntilNext = diff.TotalMinutes > 0 ? diff.TotalMinutes : minutes + diff.TotalMinutes;
var minutesToNextHalfHour = (60 - yourDateTimeVariable.Minutes) % 30;
This should do it:
int remainingMinutes = (current.Minute >= 30)
? 60 - current.Minute
: 30 - current.Minute;
var hhmm = fromTimeString.Split(':');
var mins = int.Parse(hhmm[1]);
var remainingMins = (60 - mins) % 30;
var str = "7:16";
var datetime = DateTime.ParseExact(str, "h:mm", new CultureInfo("en-US"));
var minutesPastHalfHour = datetime.Minute % 30;
var minutesBeforeHalfHour = 30 - minutesPastHalfHour;
I would use modulo + TimeSpan.TryParse:
public static int ComputeTime(string time)
{
TimeSpan ts;
if (TimeSpan.TryParse(time, out ts))
{
return (60 - ts.Minutes) % 30;
}
throw new ArgumentException("Time is not valid", "time");
}
private static void Main(string[] args)
{
string test1 = "7:27";
string test2 = "7:42";
Console.WriteLine(ComputeTime(test1));
Console.WriteLine(ComputeTime(test2));
Console.ReadLine();
}

C#/.NET Future Relative Timestamps?

I'm looking for some way to make a relative text timestamp but using future instead of past (not "2 days ago" but "in 2 days").
I'm making a personal task manager for my personal usages and I'd like it to tell me "this task is due in 2 days". But I can't seem to find nothing to convert a DateTime to that kind of timestamp.
This doesn't work for you?...
DateTime myTask = DateTime.Now.AddDays(2.0);
Update
As Reed pointed out in the comment box below, the OP might also be looking for a way to tell the time until the task is due or the time the task has been past due. I think something like this will work (note that I have not compiled this code, but it should give you a good idea):
public string PrintTaskDueTime(DateTime taskTime, DateTime currTime)
{
string result = string.Empty;
TimeSpan timeDiff = TimeSpan.Zero;
if(taskTime > currTime)
{
timeDiff = taskTime-currTime;
result = String.Format("Your task is due in {0} days and {1} hours.", timeDiff.TotalDays, timeDiff.Hours);
}
else if(taskTime == currTime)
{
result = "Your task is due now!";
}
else
{
timeDiff = currTime-taskTime;
result = String.Format("Your task is {0} days and {1} hours past due!", timeDiff.TotalDays, timeDiff.Hours);
}
return result;
}
So just call it by specifying the task time and the current time: PrintTimeDiff(taskTime, DateTime.Now);
I hope that helps.
If you have the date that it's due in a DateTime, then you can use a TimeSpan to get the time until due. For example:
TimeSpan dueDuration = dueDate - DateTime.Now;
Console.WriteLine("Due in {0} days and {1} hours.", dueDuration.TotalDays, dueDurations.Hours);
The DateTime type is used to represent specific points in time. For example, DateTime.Now.
The TimeSpan is used to represent specific durations of time. For example, TimeSpan.FromDays(2).
There are operator overloads that allow them to interact nicely with one another, For example,
DateTime dueDate = DateTime.Now + TimeSpan.FromDays(2);
A future relative timestamp is just like a past, but with the sign different.
string RelativeTime(DateTime when)
{
TimeSpan diff = when - DateTime.Now;
var minutes = (int) diff.TotalMinutes;
if (minutes == 1)
return "A minute from now";
if (minute == 2)
return "In a couple minutes";
if (minutes < 10)
return "In not 10 minutes";
if (minutes < 40)
return "In about half an hour";
/* etc */
}
The / * etc * / part is tedious and requires creativity, but that's up to you.
Based on all the replies I finally made one myself which meets all my requierements:
public static string RemainingTimeBeforeDateTime(DateTime dateTime, int level = 1)
{
int howDeep = 0;
string result = "";
TimeSpan dueDuration = dateTime - DateTime.Now;
double days = dueDuration.Days;
double hours = dueDuration.Hours;
double minutes = dueDuration.Minutes;
if (days > 0)
{
howDeep++;
result = days + "d ";
}
if (((howDeep != level) && (days != 0)) || ((days == 0) && (hours > 0)))
{
howDeep++;
result = result + hours + "h ";
}
if (((howDeep != level) && (hours != 0)) || ((hours == 0) && (minutes > 0)))
{
result = result + minutes + "m ";
}
return result;
}
Here's something I put together based on James' answer. Supports past, present, and future :)
Note: It can probably be shortened a bit more.
public static string RelativeTime(DateTime Date, string NowText = "Now")
{
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
TimeSpan TimeSpan;
double delta = 0d;
//It's in the future
if (Date > DateTime.UtcNow)
{
TimeSpan = new TimeSpan(Date.Ticks - DateTime.UtcNow.Ticks);
delta = Math.Abs(TimeSpan.TotalSeconds);
if (delta < 1 * MINUTE)
{
if (TimeSpan.Seconds == 0)
return NowText;
else
return TimeSpan.Seconds == 1 ? "A second from now" : TimeSpan.Seconds + " seconds from now";
}
if (delta < 2 * MINUTE)
return "A minute from now";
if (delta < 45 * MINUTE)
return TimeSpan.Minutes + " minutes from now";
if (delta < 90 * MINUTE)
return "An hour from now";
if (delta < 24 * HOUR)
return TimeSpan.Hours + " hours from now";
if (delta < 48 * HOUR)
return "Tomorrow";
if (delta < 30 * DAY)
return TimeSpan.Days + " days from now";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)TimeSpan.Days / 30));
return months <= 1 ? "A month from now" : months + " months from now";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)TimeSpan.Days / 365));
return years <= 1 ? "A year from now" : years + " years from now";
}
}
//It's in the past
else if (Date < DateTime.UtcNow)
{
TimeSpan = new TimeSpan(DateTime.UtcNow.Ticks - Date.Ticks);
delta = Math.Abs(TimeSpan.TotalSeconds);
if (delta < 1 * MINUTE)
{
if (TimeSpan.Seconds == 0)
return NowText;
else
return TimeSpan.Seconds == 1 ? "A second ago" : TimeSpan.Seconds + " seconds ago";
}
if (delta < 2 * MINUTE)
return "A minute ago";
if (delta < 45 * MINUTE)
return TimeSpan.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "An hour ago";
if (delta < 24 * HOUR)
return TimeSpan.Hours + " hours ago";
if (delta < 48 * HOUR)
return "Yesterday";
if (delta < 30 * DAY)
return TimeSpan.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)TimeSpan.Days / 30));
return months <= 1 ? "A month ago" : months + " months ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)TimeSpan.Days / 365));
return years <= 1 ? "A year ago" : years + " years ago";
}
}
//It's now
else
return NowText;
}

How to calculate actual months difference (calendar year not approximation) between two given dates in C#?

Example: given two dates below, finish is always greater than or equal to start
start = 2001 Jan 01
finish = 2002 Mar 15
So from 2001 Jan 01 to the end of 2002 Feb
months = 12 + 2 = 14
For 2002 March
15/30 = 0.5
so grand total is 14.5 months difference.
It's very easy to work out by hand but how do I code it elegantly? At the moment I have the combination of a lot of if else and while loops to achieve what I want but I believe there are simpler solutions out there.
Update: the output needs to be precise (not approximation) for example:
if start 2001 Jan 01 and finish 2001 Apr 16, the output should be 1 + 1 + 1= 3 (for Jan, Feb and Mar) and 16 / 31 = 0.516 month, so the total is 3.516.
Another example would be if I start on 2001 Jul 5 and finish on 2002 Jul 10, the output should be 11 month up to the end of June 2002, and (31-5)/31 = 0.839 and 10/31 = 0.323 months, so the total is 11 + 0.839 + 0.323 = 12.162.
I extended Josh Stodola's code and Hightechrider's code:
public static decimal GetMonthsInRange(this IDateRange thisDateRange)
{
var start = thisDateRange.Start;
var finish = thisDateRange.Finish;
var monthsApart = Math.Abs(12*(start.Year - finish.Year) + start.Month - finish.Month) - 1;
decimal daysInStartMonth = DateTime.DaysInMonth(start.Year, start.Month);
decimal daysInFinishMonth = DateTime.DaysInMonth(finish.Year, finish.Month);
var daysApartInStartMonth = (daysInStartMonth - start.Day + 1)/daysInStartMonth;
var daysApartInFinishMonth = finish.Day/daysInFinishMonth;
return monthsApart + daysApartInStartMonth + daysApartInFinishMonth;
}
I gave an int answer before, and then realized what you asked for a more precise answer. I was tired, so I deleted and went to bed. So much for that, I was unable to fall asleep! For some reason, this question really bugged me, and I had to solve it. So here you go...
static void Main(string[] args)
{
decimal diff;
diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2002, 3, 15));
Console.WriteLine(diff.ToString("n2")); //14.45
diff = monthDifference(new DateTime(2001, 1, 1), new DateTime(2001, 4, 16));
Console.WriteLine(diff.ToString("n2")); //3.50
diff = monthDifference(new DateTime(2001, 7, 5), new DateTime(2002, 7, 10));
Console.WriteLine(diff.ToString("n2")); //12.16
Console.Read();
}
static decimal monthDifference(DateTime d1, DateTime d2)
{
if (d1 > d2)
{
DateTime hold = d1;
d1 = d2;
d2 = hold;
}
int monthsApart = Math.Abs(12 * (d1.Year-d2.Year) + d1.Month - d2.Month) - 1;
decimal daysInMonth1 = DateTime.DaysInMonth(d1.Year, d1.Month);
decimal daysInMonth2 = DateTime.DaysInMonth(d2.Year, d2.Month);
decimal dayPercentage = ((daysInMonth1 - d1.Day) / daysInMonth1)
+ (d2.Day / daysInMonth2);
return monthsApart + dayPercentage;
}
Now I shall have sweet dreams. Goodnight :)
What you want is probably something close to this ... which pretty much follows your explanation as to how to calculate it:
var startofd1 = d1.AddDays(-d1.Day + 1);
var startOfNextMonthAfterd1 = startofd1.AddMonths(1); // back to start of month and then to next month
int daysInFirstMonth = (startOfNextMonthAfterd1 - startofd1).Days;
double fraction1 = (double)(daysInFirstMonth - (d1.Day - 1)) / daysInFirstMonth; // fractional part of first month remaining
var startofd2 = d2.AddDays(-d2.Day + 1);
var startOfNextMonthAfterd2 = startofd2.AddMonths(1); // back to start of month and then to next month
int daysInFinalMonth = (startOfNextMonthAfterd2 - startofd2).Days;
double fraction2 = (double)(d2.Day - 1) / daysInFinalMonth; // fractional part of last month
// now find whole months in between
int monthsInBetween = (startofd2.Year - startOfNextMonthAfterd1.Year) * 12 + (startofd2.Month - startOfNextMonthAfterd1.Month);
return monthsInBetween + fraction1 + fraction2;
NB This has not been tested very well but it shows how to handle problems like this by finding well known dates at the start of months around the problem values and then working off them.
While loops for date time calculations are always a bad idea: see http://www.zuneboards.com/forums/zune-news/38143-cause-zune-30-leapyear-problem-isolated.html
Depending on how exactly you want your logic to work, this would at least give you a decent approximation:
// 365 days per year + 1 day per leap year = 1461 days every 4 years
// But years divisible by 100 are not leap years
// So 1461 days every 4 years - 1 day per 100th year = 36524 days every 100 years
// 12 months per year = 1200 months every 100 years
const double DaysPerMonth = 36524.0 / 1200.0;
double GetMonthsDifference(DateTime start, DateTime finish)
{
double days = (finish - start).TotalDays;
return days / DaysPerMonth;
}
One way to do this is that you'll see around quite a bit is:
private static int monthDifference(DateTime startDate, DateTime endDate)
{
int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
return Math.Abs(monthsApart);
}
However, you want "partial months" which this doesn't give. But what is the point in comparing apples (January/March/May/July/August/October/December) with oranges (April/June/September/November) or even bananas that are sometimes coconuts (February)?
An alternative is to import Microsoft.VisualBasic and do this:
DateTime FromDate;
DateTime ToDate;
FromDate = DateTime.Parse("2001 Jan 01");
ToDate = DateTime.Parse("2002 Mar 15");
string s = DateAndTime.DateDiff (DateInterval.Month, FromDate,ToDate, FirstDayOfWeek.System, FirstWeekOfYear.System ).ToString();
However again:
The return value for
DateInterval.Month is calculated
purely from the year and month parts
of the arguments
[Source]
Just improved Josh's answer
static decimal monthDifference(DateTime d1, DateTime d2)
{
if (d1 > d2)
{
DateTime hold = d1;
d1 = d2;
d2 = hold;
}
decimal monthsApart = Math.Abs((12 * (d1.Year - d2.Year)) + d2.Month - d1.Month - 1);
decimal daysinStartingMonth = DateTime.DaysInMonth(d1.Year, d1.Month);
monthsApart = monthsApart + (1-((d1.Day - 1) / daysinStartingMonth));
// Replace (d1.Day - 1) with d1.Day incase you DONT want to have both inclusive difference.
decimal daysinEndingMonth = DateTime.DaysInMonth(d2.Year, d2.Month);
monthsApart = monthsApart + (d2.Day / daysinEndingMonth);
return monthsApart;
}
The answer works perfectly and while the terseness of the code makes it very small I had to break everything apart into smaller functions with named variables so that I could really understand what was going on... So, basically I just took Josh Stodola's code and Hightechrider's mentioned in Jeff's comment and made it smaller with comments explaining what was going on and why the calculations were being made, and hopefully this may help someone else:
[Test]
public void Calculate_Total_Months_Difference_Between_Two_Dates()
{
var startDate = DateTime.Parse( "10/8/1996" );
var finishDate = DateTime.Parse( "9/8/2012" ); // this should be now:
int numberOfMonthsBetweenStartAndFinishYears = getNumberOfMonthsBetweenStartAndFinishYears( startDate, finishDate );
int absMonthsApartMinusOne = getAbsMonthsApartMinusOne( startDate, finishDate, numberOfMonthsBetweenStartAndFinishYears );
decimal daysLeftToCompleteStartMonthPercentage = getDaysLeftToCompleteInStartMonthPercentage( startDate );
decimal daysCompletedSoFarInFinishMonthPercentage = getDaysCompletedSoFarInFinishMonthPercentage( finishDate );
// .77 + .26 = 1.04
decimal totalDaysDifferenceInStartAndFinishMonthsPercentage = daysLeftToCompleteStartMonthPercentage + daysCompletedSoFarInFinishMonthPercentage;
// 13 + 1.04 = 14.04 months difference.
decimal totalMonthsDifference = absMonthsApartMinusOne + totalDaysDifferenceInStartAndFinishMonthsPercentage;
//return totalMonths;
}
private static int getNumberOfMonthsBetweenStartAndFinishYears( DateTime startDate, DateTime finishDate )
{
int yearsApart = startDate.Year - finishDate.Year;
const int INT_TotalMonthsInAYear = 12;
// 12 * -1 = -12
int numberOfMonthsBetweenYears = INT_TotalMonthsInAYear * yearsApart;
return numberOfMonthsBetweenYears;
}
private static int getAbsMonthsApartMinusOne( DateTime startDate, DateTime finishDate, int numberOfMonthsBetweenStartAndFinishYears )
{
// This may be negative i.e. 7 - 9 = -2
int numberOfMonthsBetweenStartAndFinishMonths = startDate.Month - finishDate.Month;
// Absolute Value Of Total Months In Years Plus The Simple Months Difference Which May Be Negative So We Use Abs Function
int absDiffInMonths = Math.Abs( numberOfMonthsBetweenStartAndFinishYears + numberOfMonthsBetweenStartAndFinishMonths );
// Subtract one here because we are going to use a perecentage difference based on the number of days left in the start month
// and adding together the number of days that we've made it so far in the finish month.
int absMonthsApartMinusOne = absDiffInMonths - 1;
return absMonthsApartMinusOne;
}
/// <summary>
/// For example for 7/8/2012 there are 24 days left in the month so about .77 percentage of month is left.
/// </summary>
private static decimal getDaysLeftToCompleteInStartMonthPercentage( DateTime startDate )
{
// startDate = "7/8/2012"
// 31
decimal daysInStartMonth = DateTime.DaysInMonth( startDate.Year, startDate.Month );
// 31 - 8 = 23
decimal totalDaysInStartMonthMinusStartDay = daysInStartMonth - startDate.Day;
// add one to mark the day as being completed. 23 + 1 = 24
decimal daysLeftInStartMonth = totalDaysInStartMonthMinusStartDay + 1;
// 24 / 31 = .77 days left to go in the month
decimal daysLeftToCompleteInStartMonthPercentage = daysLeftInStartMonth / daysInStartMonth;
return daysLeftToCompleteInStartMonthPercentage;
}
/// <summary>
/// For example if the finish date were 9/8/2012 we've completed 8 days so far or .24 percent of the month
/// </summary>
private static decimal getDaysCompletedSoFarInFinishMonthPercentage( DateTime finishDate )
{
// for septebmer = 30 days in month.
decimal daysInFinishMonth = DateTime.DaysInMonth( finishDate.Year, finishDate.Month );
// 8 days divided by 30 = .26 days completed so far in finish month.
decimal daysCompletedSoFarInFinishMonthPercentage = finishDate.Day / daysInFinishMonth;
return daysCompletedSoFarInFinishMonthPercentage;
}
This solution calculates whole months and then adds the partial month based on the end of the time period. This way it always calculates full months between the dates' day-of-month and then calculates the partial month based on the number of remaining days.
public decimal getMonthDiff(DateTime date1, DateTime date2) {
// Make parameters agnostic
var earlyDate = (date1 < date2 ? date1 : date2);
var laterDate = (date1 > date2 ? date1 : date2);
// Calculate the change in full months
decimal months = ((laterDate.Year - earlyDate.Year) * 12) + (laterDate.Month - earlyDate.Month) - 1;
// Add partial months based on the later date
if (earlyDate.Day <= laterDate.Day) {
decimal laterMonthDays = DateTime.DaysInMonth(laterDate.Year, laterDate.Month);
decimal laterPartialMonth = ((laterDate.Day - earlyDate.Day) / laterMonthDays);
months += laterPartialMonth + 1;
} else {
var laterLastMonth = laterDate.AddMonths(-1);
decimal laterLastMonthDays = DateTime.DaysInMonth(laterLastMonth.Year, laterLastMonth.Month);
decimal laterPartialMonth = ((laterLastMonthDays - earlyDate.Day + laterDate.Day) / laterLastMonthDays);
months += laterPartialMonth;
}
return months;
}
The calculation below is one that is according the way the Dutch Tax Authority wants months calculated. This means that when the starts day is for example feb 22, march 23 should be result in something above 1 and not just something like 0.98.
private decimal GetMonthDiffBetter(DateTime date1, DateTime date2)
{
DateTime start = date1 < date2 ? date1 : date2;
DateTime end = date1 < date2 ? date2 : date1;
int totalYearMonths = (end.Year - start.Year) * 12;
int restMonths = end.Month - start.Month;
int totalMonths = totalYearMonths + restMonths;
decimal monthPart = (decimal)end.Day / (decimal)start.Day;
return totalMonths - 1 + monthPart;
}`
This should get you where you need to go:
DateTime start = new DateTime(2001, 1, 1);
DateTime finish = new DateTime(2002, 3, 15);
double diff = (finish - start).TotalDays / 30;
the framework as a TimeSpan object that is a result of subtracting two dates.
the subtraction is already considering the various option of February(28/29 days a month) so in my opinion this is the best practice
after you got it you can format it the way you like best
DateTime dates1 = new DateTime(2010, 1, 1);
DateTime dates2 = new DateTime(2010, 3, 15);
var span = dates1.Subtract(dates2);
span.ToString("your format here");
private Double GetTotalMonths(DateTime future, DateTime past)
{
Double totalMonths = 0.0;
while ((future - past).TotalDays > 28 )
{
past = past.AddMonths(1);
totalMonths += 1;
}
var daysInCurrent = DateTime.DaysInMonth(future.Year, future.Month);
var remaining = future.Day - past.Day;
totalMonths += ((Double)remaining / (Double)daysInCurrent);
return totalMonths;
}

Categories