最近完成了四分之一 [英] Nearest completed quarter

查看:143
本文介绍了最近完成了四分之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个C#的功能,这将给我给出一个日期最近结束的季度的最后一天?

例如,

  VAR lastDayOfLastQuarter = SomeFunction(2010年1月3日);
 

将设置lastDayOfLastQuarter = 2009年12月31号

解决方案

 公共静态的DateTime NearestQuarterEnd(这个日期为准​​){
    IEnumerable的< D​​ateTime的>考生=
        QuartersInYear(date.Year).Union(QuartersInYear(date.Year  -  1));
    返回candidates.Where(D = D 1和D&所述; date.Date).OrderBy(D = D 1和D)。去年();
}

静态的IEnumerable< D​​ateTime的> QuartersInYear(INT年){
    返回新的List< D​​ateTime的>(){
        新的日期时间(年,3,31),
        新的日期时间(年,6,30),
        新的日期时间(年,9,30),
        新的日期时间(年,12,31),
    };
}
 

用法:

 日期时间日期=新的日期时间(2010年,1,3);
日期时间quarterEnd = date.NearestQuarterEnd();
 

该方法的优点在于,如果你有四分之三的一个奇怪的定义(例如,财年比历年不同),该方法 QuartersInYear 很容易修改,处理这个问题。

Is there a C# function which will give me the last day of the most recently finished Quarter given a date?

For example,

var lastDayOfLastQuarter = SomeFunction(jan 3, 2010);

would set lastDayOfLastQuarter = Dec 31, 2009

解决方案

public static DateTime NearestQuarterEnd(this DateTime date) {
    IEnumerable<DateTime> candidates = 
        QuartersInYear(date.Year).Union(QuartersInYear(date.Year - 1));
    return candidates.Where(d => d < date.Date).OrderBy(d => d).Last();
}

static IEnumerable<DateTime> QuartersInYear(int year) {
    return new List<DateTime>() {
        new DateTime(year, 3, 31),
        new DateTime(year, 6, 30),
        new DateTime(year, 9, 30),
        new DateTime(year, 12, 31),
    };
}

Usage:

DateTime date = new DateTime(2010, 1, 3);
DateTime quarterEnd = date.NearestQuarterEnd();

This method has the advantage in that if you have an odd definition of quarters (for example, fiscal year is different than calendar year) the method QuartersInYear is easily modified to handle this.

这篇关于最近完成了四分之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆