How can I get the same results of the Excel YearFrac function in my C# application?
Calculates the fraction of the year represented by the number of whole days between two dates (the start_date and the end_date). Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or obligations to assign to a specific term.
Here is a good snippet.
The algorithm for the YearFrac function is in fact very complex. Maybe this article can provide you with more details.
You can use Excel's functionality directly to calculate YearFrac. Microsoft says you are not supposed to use it, but it works very well. If you need a 100% compatibility with Excel, this solution is hard to beat. You need to add to your project a reference to Microsoft.Office.Interop.Excel in order for this code to compile.
static void Main() {
var excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.WorksheetFunction wsf = excel.WorksheetFunction;
var start = new DateTime(1999, 11, 1);
var end = new DateTime(1999, 1, 11);
for (var basis = 0; basis != 5; basis++) {
Console.WriteLine(wsf.YearFrac(start, end, basis));
}
}
The signature of YEARFRAC is YEARFRAC(Date startDate, Date endDate, int convention). The method to calculate the YEARFRAC depends on the convention.
For convention = 2, YEARFRAC will calculate the YEARFRAC using ACT/360 method. An implementation of the ACT/360 can be found at svn.finmath.net, specifically DayCountConvention_ACT_360.java
For convention = 3, YEARFRAC will calculate the YEARFRAC using ACT/365 method. An implementation of the ACT/365 can be found at svn.finmath.net, specifically
DayCountConvention_ACT_365.java
For convention = 4, YEARFRAC will calculate the YEARFRAC using 30E/360 method. An implementation of the 30E/360 can be found at svn.finmath.net, specifically DayCountConvention_30E_360.java
For convention = 1, the documentation claims that YEARFRAC is calculate using ACT/ACT convention. However, there are a multiple versions of ACT/ACT and I believe the standard for many financial products is ACT/ACT ISDA. I found that YEARFRAC differs by a small amount from the ACT/ACT IDSA convention! An implementation of the ACT/ACT IDSA can be found at DayCountConvention_ACT_ACT_ISDA.java
I haven't checked the other act/act versions yet, but I would not rely on an emulation of YEARFRAC ACT/ACT, when it is not clear what kind of method they implement...
May I suggest:
public static double Yearfrac(DateTime startDate,DateTime endDate,DayCount daycount=DayCount.ActAct)
{
var nbDaysInPeriod = (double)(endDate - startDate).Days;
switch(daycount)
{
case (DayCount.Act360):
return nbDaysInPeriod / (double)360;
case (DayCount.Act365):
return nbDaysInPeriod / (double)365;
case (DayCount.ActAct):
return GetActAct(startDate,endDate);
case (DayCount.Days360):
var result = (endDate.Year - startDate.Year) * 360.0 + (endDate.Month - startDate.Month) * 30.0 + (Math.Min(endDate.Day, 30.0) - Math.Min(startDate.Day, 30.0));
return result/360;
default:
return nbDaysInPeriod / (double)365;
}
}
public static double GetActAct(DateTime startDate, DateTime endDate)
{
// Reproduce Excel Yearfrac as per http://www.dwheeler.com/yearfrac/excel-ooxml-yearfrac.pdf
var nbDaysInPeriod = (double)(endDate - startDate).Days;
if(startDate.Year==endDate.Year || (endDate.Year-1==startDate.Year&&(startDate.Month>endDate.Month||startDate.Month==endDate.Month&&(startDate.Day>=endDate.Day))))
{
var den = 365.0;
if (startDate.Year == endDate.Year && DateTime.IsLeapYear(startDate.Year))
{
den++;
}
else
{
if (endDate.Day == 29 && endDate.Month == 2)
{
den++;
}
else
{
if (DateTime.IsLeapYear(startDate.Year))
{
var feb = new DateTime(startDate.Year, 2, 29);
if (startDate<=feb && feb<=endDate) den++;
}
else
{
if (DateTime.IsLeapYear(endDate.Year))
{
var feb = new DateTime(endDate.Year, 2, 29);
if (startDate <= feb && feb <= endDate) den++;
}
}
}
}
}
else
{
var nbYears = endDate.Year - startDate.Year+1;
var den = nbYears * 365.0;
for (var i=0;i<nbYears;i++)
{
if (DateTime.IsLeapYear(startDate.Year + i)) den++;
}
den /= nbYears;
return nbDaysInPeriod / den;
}
return nbDaysInPeriod / 365.0;
}
If you want an exact YEARFRAC which measures to the day (so no need to specify any day-count convention) and gives a negative for periods in the past try this date extension...
public static double YearFrac(this DateTime startDate, DateTime endDate)
{
//---------------------------------------------------------------------------
startDate = DateTime.Parse(startDate.ToString("dd-MMM-yyyy"));
endDate = DateTime.Parse(endDate.ToString("dd-MMM-yyyy"));
//---------------------------------------------------------------------------
if (startDate == endDate)
return 0.0;
//---------------------------------------------------------------------------
double reverse = 1.0;
//---------------------------------------------------------------------------
if (startDate > endDate)
{
var ed = endDate;
endDate = startDate;
startDate = ed;
reverse = -1.0;
}
//---------------------------------------------------------------------------
int y1 = startDate.Year;
int y2 = endDate.Year;
int m1 = startDate.Month;
int m2 = endDate.Month;
int d1 = startDate.Day;
int d2 = endDate.Day;
int diy = startDate.DaysInYear();
int days = (endDate - startDate).Days;
//---------------------------------------------------------------------------
if (y1 == y2)
{
return (double)days / (double)diy * reverse;
}
//---------------------------------------------------------------------------
int wholeyears = y2 - y1 - 1;
DateTime lastDateA = ValidDate(y2 - 1, m2, d2);
DateTime lastDateB = ValidDate(y2 - 1, m1, d1);
int period1 = (endDate - lastDateA).Days;
int period2 = (endDate - lastDateB).Days;
//---------------------------------------------------------------------------
if (m1 > m2 || (m1 == m2 && d1 > d2))
{
return ((double)wholeyears + (double)period2 / (double)period1) * reverse;
}
//---------------------------------------------------------------------------
DateTime lastDateC = ValidDate(y2, m1, d1);
int period3 = (endDate - lastDateC).Days;
//---------------------------------------------------------------------------
return ((double)wholeyears + 1.0 + (double)period3 / (double)period1) * reverse;
//---------------------------------------------------------------------------
}
public static DateTime ValidDate(int y, int m, int d)
{
try
{
DateTime dt1 = new DateTime(y, m, d);
return dt1;
}
catch (Exception)
{
try
{
if (d == 29 && m == 2)
{
return new DateTime(y, 3, 1);
}
return new DateTime(y, m, d);
}
catch (Exception)
{
throw;
}
}
}
public static int DaysInYear(this DateTime date)
{
int year = date.Year;
DateTime d1 = DateTime.Parse("01-Jan-" + year.ToString());
DateTime d2 = DateTime.Parse("01-Jan-" + (year + 1).ToString());
int diy = (d2 - d1).Days;
return diy;
}
Related
Hi I was solving a problem to calculate some library fine based on difference in return date and due date in C#. Now there are some constraints to the problem like
if the return year is changed i.e. if the return year is greater than the due date calendar year then fine is 10000. e.g. due date "31/12/2015" and return date "01/01/2016" then also fine is 10000.
if the return month is changed then fine is 500 * number of months late.
if the return day is changed then fine is 15 * number of days late.
else fine is 0.
Now i wrote the function below:
static int CalcFine (int[] returnedOn, int[] dueOn) {
int returnD = returnedOn[0];
int returnM = returnedOn[1];
int returnY = returnedOn[2];
int dueD = dueOn[0];
int dueM = dueOn[1];
int dueY = dueOn[2];
if (returnY > dueY) {
return 10000;
} else if (returnY < dueY) {
return 0;
} else {
if (returnM > dueM) {
return (returnM - dueM) * 500;
} else if (returnM < dueM) {
return 0;
} else {
if (returnD > dueD) {
return (returnD - dueD) * 15;
} else {
return 0;
}
}
}
}
I read about the DateTime class in C# that has pretty neat functions that return the difference in two dates as total days, total minutes, etc. But given the constraint of Fine being different based on year, month and days, I am not sure if there is any other inbuilt function to solve the above problem. In short I am trying to find if there is another simple way to solve the above problem without using so many if-else's.
You can get the difference in days, hours or minutes.
DateTime fromdate = new DateTime(2012,1,1);
DateTime todate = DateTime.Now;
TimeSpan diff = todate - fromdate;
int differenceInDays = diff.Days;
If you want to try differently for your validations and business rules. Follow the below code
public double GetFineAmount(DateTime DueDate)
{
DateTime dt = DateTime.Now;
int yeardiff, monthdiff, daydiff;
yeardiff = dt.Year - DueDate.Year;
if (yeardiff > 0) return 10000;
monthdiff = dt.Month - DueDate.Month;
if (monthdiff > 0) return 500 * monthdiff;
daydiff = dt.Day - DueDate.Day;
if (daydiff > 0) return 15 * daydiff;
return 0;
}
Editted again.. changed string pattern. I guess I need some sleep...
static int CalcFine (string returnedOn, string dueOn)
{
DateTime returnedDate = DateTime.ParseExact(
returnedOn, "d M yyyy", CultureInfo.InvariantCulture);
DateTime dueDate = DateTime.ParseExact(
dueOn, "d M yyyy", CultureInfo.InvariantCulture);
if (returnedDate < dueDate)
return 0;
if (returnedDate.Year > dueDate.Year)
return 10000;
if (returnedDate.Month > dueDate.Month)
return 500 * (returnedDate.Month - dueDate.Month);
if (returnedDate.Day > dueDate.Day)
return 15 * (returnedDate.Day - dueDate.Day);
else
return 0;
}
DateTime is a powerful tool. But you don't want to over-complicate this.
If you just find the difference between the two dates in days, the equation becomes a lot easier to manage versus trying to subtract dates.
static int CalcFine(DateTime returnedOn, DateTime dueOn)
{
TimeSpan dateDiff = (returnedOn - dueOn);
int TotalDays = dateDiff.Days;
if (TotalDays >= 365)
{
return 10000;
}
else if(TotalDays < 365 && TotalDays > 30 && TotalDays % 30 > 1)
{
return (500 * (TotalDays % 30));
}
else if(TotalDays < 30 && TotalDays > 0)
{
return 15 * TotalDays;
}
else
{
return 0;
}
}
How do I calculate Excel's XIRR function using C#?
According to XIRR function openoffice documentation (formula is same as in excel) you need to solve for XIRR variable in the following f(xirr) equation:
You can calculate xirr value by:
calculating derivative of above function -> f '(xirr)
after having f(xirr) and f'(xirr) you can solve for xirr value by using iterative Newton's method - famous formula->
EDIT
I've got a bit of time so, here it is - complete C# code for XIRR calculation:
class xirr
{
public const double tol = 0.001;
public delegate double fx(double x);
public static fx composeFunctions(fx f1, fx f2) {
return (double x) => f1(x) + f2(x);
}
public static fx f_xirr(double p, double dt, double dt0) {
return (double x) => p*Math.Pow((1.0+x),((dt0-dt)/365.0));
}
public static fx df_xirr(double p, double dt, double dt0) {
return (double x) => (1.0/365.0)*(dt0-dt)*p*Math.Pow((x+1.0),(((dt0-dt)/365.0)-1.0));
}
public static fx total_f_xirr(double[] payments, double[] days) {
fx resf = (double x) => 0.0;
for (int i = 0; i < payments.Length; i++) {
resf = composeFunctions(resf,f_xirr(payments[i],days[i],days[0]));
}
return resf;
}
public static fx total_df_xirr(double[] payments, double[] days) {
fx resf = (double x) => 0.0;
for (int i = 0; i < payments.Length; i++) {
resf = composeFunctions(resf,df_xirr(payments[i],days[i],days[0]));
}
return resf;
}
public static double Newtons_method(double guess, fx f, fx df) {
double x0 = guess;
double x1 = 0.0;
double err = 1e+100;
while (err > tol) {
x1 = x0 - f(x0)/df(x0);
err = Math.Abs(x1-x0);
x0 = x1;
}
return x0;
}
public static void Main (string[] args)
{
double[] payments = {-6800,1000,2000,4000}; // payments
double[] days = {01,08,16,25}; // days of payment (as day of year)
double xirr = Newtons_method(0.1,
total_f_xirr(payments,days),
total_df_xirr(payments,days));
Console.WriteLine("XIRR value is {0}", xirr);
}
}
BTW, keep in mind that not all payments will result in valid XIRR because of restrictions of formula and/or Newton method!
cheers!
I started with 0x69's solution but eventually some new scenarios caused Newton's Method to fail. I created a "smart" version, which uses Bisection Method (slower) when Newton's fails.
Please notice the inline references to multiple sources I used for this solution.
Finally, you are not going to be able to reproduce some of these scenarios in Excel, for Excel itself uses Newton's method. Refer to XIRR, eh? for an interesting discussion about this.
using System;
using System.Collections.Generic;
using System.Linq;
// See the following articles:
// http://blogs.msdn.com/b/lucabol/archive/2007/12/17/bisection-based-xirr-implementation-in-c.aspx
// http://www.codeproject.com/Articles/79541/Three-Methods-for-Root-finding-in-C
// http://www.financialwebring.org/forum/viewtopic.php?t=105243&highlight=xirr
// Default values based on Excel doc
// http://office.microsoft.com/en-us/excel-help/xirr-function-HP010062387.aspx
namespace Xirr
{
public class Program
{
private const Double DaysPerYear = 365.0;
private const int MaxIterations = 100;
private const double DefaultTolerance = 1E-6;
private const double DefaultGuess = 0.1;
private static readonly Func<IEnumerable<CashItem>, Double> NewthonsMethod =
cf => NewtonsMethodImplementation(cf, Xnpv, XnpvPrime);
private static readonly Func<IEnumerable<CashItem>, Double> BisectionMethod =
cf => BisectionMethodImplementation(cf, Xnpv);
public static void Main(string[] args)
{
RunScenario(new[]
{
// this scenario fails with Newton's but succeeds with slower Bisection
new CashItem(new DateTime(2012, 6, 1), 0.01),
new CashItem(new DateTime(2012, 7, 23), 3042626.18),
new CashItem(new DateTime(2012, 11, 7), -491356.62),
new CashItem(new DateTime(2012, 11, 30), 631579.92),
new CashItem(new DateTime(2012, 12, 1), 19769.5),
new CashItem(new DateTime(2013, 1, 16), 1551771.47),
new CashItem(new DateTime(2013, 2, 8), -304595),
new CashItem(new DateTime(2013, 3, 26), 3880609.64),
new CashItem(new DateTime(2013, 3, 31), -4331949.61)
});
RunScenario(new[]
{
new CashItem(new DateTime(2001, 5, 1), 10000),
new CashItem(new DateTime(2002, 3, 1), 2000),
new CashItem(new DateTime(2002, 5, 1), -5500),
new CashItem(new DateTime(2002, 9, 1), 3000),
new CashItem(new DateTime(2003, 2, 1), 3500),
new CashItem(new DateTime(2003, 5, 1), -15000)
});
}
private static void RunScenario(IEnumerable<CashItem> cashFlow)
{
try
{
try
{
var result = CalcXirr(cashFlow, NewthonsMethod);
Console.WriteLine("XIRR [Newton's] value is {0}", result);
}
catch (InvalidOperationException)
{
// Failed: try another algorithm
var result = CalcXirr(cashFlow, BisectionMethod);
Console.WriteLine("XIRR [Bisection] (Newton's failed) value is {0}", result);
}
}
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}
catch (InvalidOperationException exception)
{
Console.WriteLine(exception.Message);
}
}
private static double CalcXirr(IEnumerable<CashItem> cashFlow, Func<IEnumerable<CashItem>, double> method)
{
if (cashFlow.Count(cf => cf.Amount > 0) == 0)
throw new ArgumentException("Add at least one positive item");
if (cashFlow.Count(c => c.Amount < 0) == 0)
throw new ArgumentException("Add at least one negative item");
var result = method(cashFlow);
if (Double.IsInfinity(result))
throw new InvalidOperationException("Could not calculate: Infinity");
if (Double.IsNaN(result))
throw new InvalidOperationException("Could not calculate: Not a number");
return result;
}
private static Double NewtonsMethodImplementation(IEnumerable<CashItem> cashFlow,
Func<IEnumerable<CashItem>, Double, Double> f,
Func<IEnumerable<CashItem>, Double, Double> df,
Double guess = DefaultGuess,
Double tolerance = DefaultTolerance,
int maxIterations = MaxIterations)
{
var x0 = guess;
var i = 0;
Double error;
do
{
var dfx0 = df(cashFlow, x0);
if (Math.Abs(dfx0 - 0) < Double.Epsilon)
throw new InvalidOperationException("Could not calculate: No solution found. df(x) = 0");
var fx0 = f(cashFlow, x0);
var x1 = x0 - fx0/dfx0;
error = Math.Abs(x1 - x0);
x0 = x1;
} while (error > tolerance && ++i < maxIterations);
if (i == maxIterations)
throw new InvalidOperationException("Could not calculate: No solution found. Max iterations reached.");
return x0;
}
internal static Double BisectionMethodImplementation(IEnumerable<CashItem> cashFlow,
Func<IEnumerable<CashItem>, Double, Double> f,
Double tolerance = DefaultTolerance,
int maxIterations = MaxIterations)
{
// From "Applied Numerical Analysis" by Gerald
var brackets = Brackets.Find(Xnpv, cashFlow);
if (Math.Abs(brackets.First - brackets.Second) < Double.Epsilon)
throw new ArgumentException("Could not calculate: bracket failed");
Double f3;
Double result;
var x1 = brackets.First;
var x2 = brackets.Second;
var i = 0;
do
{
var f1 = f(cashFlow, x1);
var f2 = f(cashFlow, x2);
if (Math.Abs(f1) < Double.Epsilon && Math.Abs(f2) < Double.Epsilon)
throw new InvalidOperationException("Could not calculate: No solution found");
if (f1*f2 > 0)
throw new ArgumentException("Could not calculate: bracket failed for x1, x2");
result = (x1 + x2)/2;
f3 = f(cashFlow, result);
if (f3*f1 < 0)
x2 = result;
else
x1 = result;
} while (Math.Abs(x1 - x2)/2 > tolerance && Math.Abs(f3) > Double.Epsilon && ++i < maxIterations);
if (i == maxIterations)
throw new InvalidOperationException("Could not calculate: No solution found");
return result;
}
private static Double Xnpv(IEnumerable<CashItem> cashFlow, Double rate)
{
if (rate <= -1)
rate = -1 + 1E-10; // Very funky ... Better check what an IRR <= -100% means
var startDate = cashFlow.OrderBy(i => i.Date).First().Date;
return
(from item in cashFlow
let days = -(item.Date - startDate).Days
select item.Amount*Math.Pow(1 + rate, days/DaysPerYear)).Sum();
}
private static Double XnpvPrime(IEnumerable<CashItem> cashFlow, Double rate)
{
var startDate = cashFlow.OrderBy(i => i.Date).First().Date;
return (from item in cashFlow
let daysRatio = -(item.Date - startDate).Days/DaysPerYear
select item.Amount*daysRatio*Math.Pow(1.0 + rate, daysRatio - 1)).Sum();
}
public struct Brackets
{
public readonly Double First;
public readonly Double Second;
public Brackets(Double first, Double second)
{
First = first;
Second = second;
}
internal static Brackets Find(Func<IEnumerable<CashItem>, Double, Double> f,
IEnumerable<CashItem> cashFlow,
Double guess = DefaultGuess,
int maxIterations = MaxIterations)
{
const Double bracketStep = 0.5;
var leftBracket = guess - bracketStep;
var rightBracket = guess + bracketStep;
var i = 0;
while (f(cashFlow, leftBracket)*f(cashFlow, rightBracket) > 0 && i++ < maxIterations)
{
leftBracket -= bracketStep;
rightBracket += bracketStep;
}
return i >= maxIterations
? new Brackets(0, 0)
: new Brackets(leftBracket, rightBracket);
}
}
public struct CashItem
{
public DateTime Date;
public Double Amount;
public CashItem(DateTime date, Double amount)
{
Date = date;
Amount = amount;
}
}
}
}
Thanks to contributors of the nuget package located at Excel Financial Functions. It supports many financial methods - AccrInt, Irr, Npv, Pv, XIrr, XNpv, etc.,
Install and import the package.
As all the methods are static in Financial class, directly call specific method as Financial.<method_name> with required parameters.
Example:
using Excel.FinancialFunctions;
namespace ExcelXirr
{
class Program
{
static void Main(string[] args)
{
List<double> valList =new List<double>();
valList.Add(4166.67);
valList.Add(-4166.67);
valList.Add(-4166.67);
valList.Add(-4166.67);
List<DateTime> dtList = new List<DateTime>();
dtList.Add(new DateTime(2014, 9, 1));
dtList.Add(new DateTime(2014, 10, 1));
dtList.Add(new DateTime(2014, 11, 1));
dtList.Add(new DateTime(2014, 12, 1));
double result = Financial.XIrr(valList, dtList);
Console.WriteLine(result);
Console.ReadLine();
}
}
}
Result is same as Excel.
The other answers show how to implement XIRR in C#, but if only the calculation result is needed you can call Excel's XIRR function directly in the following way:
First add reference to Microsoft.Office.Interop.Excel and then use the following method:
public static double Xirr(IList<double> values, IList<DateTime> dates)
{
var xlApp = new Application();
var datesAsDoubles = new List<double>();
foreach (var date in dates)
{
var totalDays = (date - DateTime.MinValue).TotalDays;
datesAsDoubles.Add(totalDays);
}
var valuesArray = values.ToArray();
var datesArray = datesAsDoubles.ToArray();
return xlApp.WorksheetFunction.Xirr(valuesArray, datesArray);
}
This repo from GitHub - klearlending/XIRR has sample code on how to calculate XIRR.
The author also provided a blogpost XIRR-demystified, that explains the logic and reasoning.
So far that lib is giving close to accurate results for me. (Still exploring it and forked it for personal use)
I have my start date as 05/03/2012 and duration is 200 days now I would like to get the end date excluding sundays. So that my end date should be 05/02/2013.. Can some one help me
Try this for me:
var startDate = new DateTime(2012, 5, 3);
var sundaysOverDuration = 200 / 7;
var actualDuration = 200 + sundaysOverDuration;
var newDate = startDate.AddDays(actualDuration);
I also honestly have to admit that this link is flat out elegant surrounding how it handles a lot of the exceptions that exist when doing these types of calculations. I'm not sure you need something that complex, but it's worth letting you know. I'm going to inline the code just to ensure it's preserved if the link is ever broken.
public static double GetBusinessDays(DateTime startD, DateTime endD)
{
double calcBusinessDays =
1 + ((endD-startD).TotalDays * 6 -
(startD.DayOfWeek-endD.DayOfWeek) * 2) / 7;
if ((int)startD.DayOfWeek == 0) calcBusinessDays --;
return calcBusinessDays;
}
public static DateTime AddWorkDaysToStartDate(DateTime startD, double businessDays)
{
int DoW = (int)startD.DayOfWeek;
double temp = businessDays + DoW + 1;
if (DoW != 0) temp --;
DateTime calcendD = startD.AddDays(
Math.Floor(temp / 6)*2-DoW + temp
- 2* Convert.ToInt32(temp % 6 == 0)) ;
}
Finally, based on your question it doesn't appear you need to handle holidays, but if you do the solution is much more complex and would need to be database driven, so just keep that in mind.
You can use the CalendarDateAdd class from the Time Period Library for .NET:
// ----------------------------------------------------------------------
public void AddDaysSample()
{
CalendarDateAdd calendarDateAdd = new CalendarDateAdd();
calendarDateAdd.AddWorkingWeekDays();
calendarDateAdd.WeekDays.Add( DayOfWeek.Saturday );
DateTime start = new DateTime( 2012, 5, 3 );
TimeSpan duration = new TimeSpan( 200, 0, 0, 0 );
DateTime? end = calendarDateAdd.Add( start, duration );
Console.WriteLine( "AddDaysSample : {0:d} + {1} days = {2:d}", start, duration.Days, end );
} // AddDaysSample
I'm trying to make a calendar using wpf. By using itemsPanel and more, I have a grid with 7 columns(sunday-saturday) and 6 rows(week# of month). If i can find the starting position of the first of each month by getting the weekday and week number(of the month), how can I find the week number(0-5 of each month)? Also can't I somehow just fill in the calendar from there? I'm lost and I don't know what else to try.
public partial class SchedulePage : Page
{
MainWindow _parentForm;
public int dayofweek;
public SchedulePage(MainWindow parentForm)
{
InitializeComponent();
_parentForm = parentForm;
// DateTime date = new DateTime(year, month, day);
_parentForm.bindings = new BindingCamper();
_parentForm.bindings.schedule.Add(new Schedule { WeekNo = (int) getWeekNumber(), WeekDay = dayofweek });
DataContext = _parentForm.bindings;
// lblTest.Content = dates(2011, 10, 27);
}
public double getWeekNumber()
{
dayofweek = getWeekDay(2011, 10, 31);
double h = dayofweek / 7;
double g = Math.Floor(h);
return g;
}
public int getWeekDay(int year, int month, int day)
{
//year = 2011;
//month = 10;
//day = 27;
int[] t = { 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
// year -= month < 3;
return (year + year / 4 - year / 100 + year / 400 + t[month - 1] + day) % 7;
}
You must use Calendar.GetDayOfWeek and Calendar.GetWeekOfYear in preference to writing yourself.
You can guarantee that if you write any date / time handling code yourself it will contain faults and won't work in different locales.
public class Row
{
public string MonthWeek { get; set; }
public string Year { get; set; }
public string Month { get; set; }
public string Day { get; set; }
public string WeekOfYear { get; set; }
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var l = new List<Row>();
DateTime startDate = DateTime.Now;
DateTime d = new DateTime(startDate.Year, startDate.Month, 1);
var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
var ms = cal.GetWeekOfYear(new DateTime(d.Year, d.Month, 1), System.Globalization.CalendarWeekRule.FirstDay, System.DayOfWeek.Sunday);
for (var i = 1; d.Month == startDate.Month; d = d.AddDays(1))
{
var si = new Row();
var month_week = (d.Day / 7) + 1;
si.MonthWeek = month_week.ToString();
si.Month = d.Year.ToString();
si.Year = d.Month.ToString();
si.Day = d.Day.ToString();
si.WeekOfYear = cal.GetWeekOfYear(d, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString();
l.Add(si);
}
dataGrid1.ItemsSource = l;
}
}
together with the obligatory DataGrid in the XAML:
<DataGrid AutoGenerateColumns="true" Name="dataGrid1" />
You can use Calendar.GetWeekOfYear from Globalization to do this.
Here's the MSDN docs for it: http://msdn.microsoft.com/en-us/library/system.globalization.calendar.getweekofyear.aspx
You should pass the appropriate culture properties from CultureInfo.CurrentCulture to GetWeekOfYear so that you match the current culture properly.
Example:
int GetWeekOfYear(DateTime date)
{
return Calendar.GetWeekOfYear(
date,
CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule,
CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek
);
}
You could easily modify this into an extension method on DateTime:
static int GetWeekOfYear(this DateTime date)
{
return Calendar.GetWeekOfYear(
date,
CultureInfo.CurrentCulture.DateTimeFormat.CalendarWeekRule,
CultureInfo.CurrentCulture.DateTimeFormat.FirstDayOfWeek
);
}
With #Polynomial answer, I have this error:
An object reference is required for the non-static field, method, or property...
If you instanciate GregorianCalendar before then you can call the method GetWeekOfYear !
private static int GetWeekNumber(DateTime time)
{
GregorianCalendar cal = new GregorianCalendar();
int week = cal.GetWeekOfYear(time, CalendarWeekRule.FirstFullWeek, DayOfWeek.Monday);
return week;
}
I'm doing DateTime comparison but I don't want to do comparison at second, millisecond and ticks level. What's the most elegant way?
If I simply compare the DateTime, then they are seldom equal due to ticks differences.
What about using a timespan.
if (Math.Truncate((A - B).TotalMinutes) == 0)
{
//There is less than one minute between them
}
Probably not the most elegant way, but it allows for cases which are one second apart and yet have different days/hours/minutes parts such as going over midnight.
Edit: it occured to me that the truncate is unecessary...
if (Math.Abs((A - B).TotalMinutes) < 1)
{
//There is less than one minute between them
}
Personally I think this is more elegant...
One approach could be to create two new DateTimes from your values you want to compare, but ignore anything from the seconds on down and then compare those:
DateTime compare1 = new DateTime(year1, month1, day1, hour1, minute1, 0);
DateTime compare2 = new DateTime(year2, month2, day2, hour2, minute2, 0);
int result = DateTime.Compare(compare1, compare2);
I'd be the first to admit it's not elegant, but it solves the problem.
Using a TimeSpan you get all the granularity you want :
DateTime dt1, dt2;
double d = (dt2 - dt1).TotalDays;
double h = (dt2 - dt1).TotalHours;
double m = (dt2 - dt1).TotalMinutes;
double s = (dt2 - dt1).TotalSeconds;
double ms = (dt2 - dt1).TotalMilliseconds;
double ticks = (dt2 - dt1).Ticks;
public class DateTimeComparer : Comparer<DateTime>
{
private Prescision _Prescision;
public enum Prescision : sbyte
{
Millisecons,
Seconds,
Minutes,
Hour,
Day,
Month,
Year,
Ticks
}
Func<DateTime, DateTime>[] actions = new Func<DateTime, DateTime>[]
{
(x) => { return x.AddMilliseconds(-x.Millisecond);},
(x) => { return x.AddSeconds(-x.Second);},
(x) => { return x.AddMinutes(-x.Minute);},
(x) => { return x.AddHours(-x.Hour);},
(x) => { return x.AddDays(-x.Day);},
(x) => { return x.AddMonths(-x.Month);},
};
public DateTimeComparer(Prescision prescision = Prescision.Ticks)
{
_Prescision = prescision;
}
public override int Compare(DateTime x, DateTime y)
{
if (_Prescision == Prescision.Ticks)
{
return x.CompareTo(y);
}
for (sbyte i = (sbyte)(_Prescision - 1); i >= 0; i--)
{
x = actions[i](x);
y = actions[i](y);
}
return x.CompareTo(y);
}
}
Usage example:
new DateTimeComparer(DateTimeComparer.Prescision.Day).Compare(Date1, Date2)
How about this ComparerClass?
public class DateTimeComparer : Comparer<DateTime>
{
private string _Format;
public DateTimeComparer(string format)
{
_Format = format;
}
public override int Compare(DateTime x, DateTime y)
{
if(x.ToString(_Format) == y.ToString(_Format))
return 0;
return x.CompareTo(y);
}
}
This can be used by
List.Sort(new DateTimeComparer("hh:mm"));
You can convert them to String format and compare the string with each other.
This also gives freedom to choose your comparison parameters, like only the time without the date, etc.
if (String.Format("{0:ddMMyyyyHHmmss}", date1) == String.Format("{0:ddMMyyyyHHmmss}", date2))
{
// success
}
I've written this to help myself:
internal class ImpreciseCompareDate : IComparer<DateTime>
{
private readonly double _Tolerance;
public ImpreciseCompareDate(double MillisecondsTolerance)
{
_Tolerance = MillisecondsTolerance;
}
public int Compare(DateTime x, DateTime y)
{
return Math.Abs((x - y).TotalMilliseconds) < _Tolerance ? 0 : x.CompareTo(y);
}
}
Tolerance can be set to (10d/3d) to account for SQL servers 1/300th of a ms. If tolerance is exceeded, delegate to default comparer.
Another way is to convert first by processing on ticks level with a simple (non-rounding) calculation:
var now = DateTime.UtcNow;
// 636340541021531973, 2017-06-26T06:08:22.1531973Z
var millisecondsPrecision = new DateTime(now.Ticks / 10000 * 10000, now.Kind);
// 636340541021530000, 2017-06-26T06:08:22.1530000Z
var secondsPrecision = new DateTime(now.Ticks / 10000000 * 10000000, now.Kind);
// 636340541020000000, 2017-06-26T06:08:22.0000000Z
var minutePrecision = new DateTime(now.Ticks / (10000000*60) * (10000000*60), now.Kind);
// 636340541000000000, 2017-06-26T06:08:00.0000000Z
#ALZ's solution looks nice but it's too complicated and has a bug.
So I decided to combine it with #ChrisF's solution.
public class DateTimeComparer : Comparer<DateTime>
{
public enum Precision
{
Years = 0,
Months,
Days,
Hours,
Minutes,
Seconds,
Millisecons,
Ticks
}
private Precision _precision;
public DateTimeComparer(Precision precision = Precision.Ticks)
{
_precision = precision;
}
public override int Compare(DateTime x, DateTime y)
{
if (_precision == Precision.Ticks)
{
return x.CompareTo(y);
}
var xx = AssembleValue(x, _precision);
var yy = AssembleValue(y, _precision);
return xx.CompareTo(yy);
}
private static DateTime AssembleValue(DateTime input, Precision precision)
{
var p = (int)precision;
var i = 1;
return new DateTime(input.Year,
p >= i++ ? input.Month : 1,
p >= i++ ? input.Day : 1,
p >= i++ ? input.Hour : 0,
p >= i++ ? input.Minute : 0,
p >= i++ ? input.Second : 0,
p >= i++ ? input.Millisecond : 0);
}
}
Very simple solution from my own code:
TimeSpan timeDifference = presentLastSavedDate.Subtract(previousLastSavedDate);
if (timeDifference.Seconds > 0)
{
return Content(HttpStatusCode.Conflict, ALREADY_CHANGED_MSG);
}
I have create a very fast compare functions to compare DateTime with different Precission. All are arithmetical calculations and no new object are created.
public enum DateTimeComparePrecision : long
{
Millisecond = TimeSpan.TicksPerMillisecond,
Second = TimeSpan.TicksPerSecond,
Minute = TimeSpan.TicksPerMinute,
Hour = TimeSpan.TicksPerHour,
Day = TimeSpan.TicksPerDay,
}
public static bool DatesAreEqual(DateTime d1, DateTime d2, DateTimeComparePrecision Precision)
{
return (d1.Ticks - (d1.Ticks % (long)Precision)) == (d2.Ticks - (d2.Ticks % (long)Precision));
}
public static int DatesCompare(DateTime d1, DateTime d2, DateTimeComparePrecision Precision)
{
long Day1 = (d1.Ticks - (d1.Ticks % (long)Precision));
long Day2 = (d2.Ticks - (d2.Ticks % (long)Precision));
if (Day2 > Day1)
return 1;
if (Day2 < Day1)
return -1;
return 0;
}
How Ticks Transformed for the compare
DateTime NowIs = DateTime.UtcNow;
Console.WriteLine($"{NowIs:dd MM yyyy HH:mm:ss.fffffff}");
DateTime d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerMillisecond)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerSecond)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerMinute)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerHour)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerDay)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
output
01 03 2022 12:51:26.7237323
01 03 2022 12:51:26.7230000
01 03 2022 12:51:26.0000000
01 03 2022 12:51:00.0000000
01 03 2022 12:00:00.0000000
01 03 2022 00:00:00.0000000