计算当月周在.NET中 [英] Calculate week of month in .NET

查看:166
本文介绍了计算当月周在.NET中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行.NET库有返回的星期数给定日期的一个简单的方法?例如,年= 2010,月= 1天= 25 ,应该输出 5 输入的周数

Do the .NET libraries have an easy way of returning the week number for a given date? For example, input of Year = 2010, Month = 1, Day = 25, should output 5 for the week number.

最近我发现了 Calendar.GetWeekOfYear ,这是几乎没有。

Closest I found was Calendar.GetWeekOfYear, which is almost there.

Java有一个日期字符串格式为W,它返回一周一个月,但我看不到任何东西在.NET等价的。

Java has a date string format "W" which returns week in month but I can't see anything equivalent in .NET.

推荐答案

有没有内置的方式来做到这一点,但这里要说的是应该做的工作适合你的扩展方法:

There is no built in way to do this but here is an extension method that should do the job for you:

static class DateTimeExtensions {
    static GregorianCalendar _gc = new GregorianCalendar();
    public static int GetWeekOfMonth(this DateTime time) {
        DateTime first = new DateTime(time.Year, time.Month, 1);
        return time.GetWeekOfYear() - first.GetWeekOfYear() + 1;
    }

    static int GetWeekOfYear(this DateTime time) {
        return _gc.GetWeekOfYear(time, CalendarWeekRule.FirstDay, DayOfWeek.Sunday);
    }
}

用法:

DateTime time = new DateTime(2010, 1, 25);
Console.WriteLine(time.GetWeekOfMonth());

输出:

5

您可以 GetWeekOfYear 根据自己的需要改变。

You can alter GetWeekOfYear according to your needs.

这篇关于计算当月周在.NET中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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