如何计算给定日期的星期数? [英] How do I calculate the week number given a date?

查看:183
本文介绍了如何计算给定日期的星期数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有个约会,我怎么计算的星期数为一年之内该日期?

例如,在2008年1月1号至1月6日在1周和1月7日至13日在2周,所以如果我的日期是2008年1月10号,我的周数是2。

这是算法将是巨大的,让我开始和样品code也将帮助 - 我在Windows上开发的C ++

相关报道:

  

<一个href="http://stackoverflow.com/questions/348880/getting-week-number-off-a-date-in-ms-sql-server-2005">Getting周数关在MS SQL Server中的日期2005年?

解决方案

伪code:

  INT朱利安= getDayOfYear(指明MyDate)// 1月1日= 1,扬2 = 2,等等。
诠释道= getDayOfWeek(指明MyDate)//孙= 0,星期一= 1,等等。
INT dowJan1 = getDayOfWeek(1/1 /+ thisYear)//发现今年的一天第一
// INT badWeekNum =(朱利安/ 7)+ 1 //获取我们的周#(错了!不要用这个)
INT WEEKNUM =((朱利安+ 6)/ 7)//可能会更好。检查此行。 (见注释)。
如果(DOW&LT; dowJan1)//调整是星期六周#1后,
    ++ WEEKNUM;
返程(WEEKNUM)
 

要澄清一下,这个算法假定您的编号周是这样的:

  S MŤW R五六
            1 2 3';  - 周#1
4 5 6 7 8 9 10 LT;  - 周#2
[等等。]
 

getDayOfWeek()和getDayOfYear()是大多数语言标准的日期对象操作。如果你没有他们,你可以算进一些已知的日期(1970年1月1日是一个普通的一种),抬头看到它是星期几后。

如果你要实现你自己的日期计算程序,记得几年是被100整除的是不会闰年,除非它们也被400整除所以1900是不是闰年年,但2000年。如果你去上班早的时候,你要惹公历VS罗马儒略历,等等,看的维基百科,获取的信息上载。

有关日期/时间函数在Windows此链接讲座/ C ++更详细。

If I have a date, how do I calculate the week number for that date within that year?

For example, in 2008, January 1st to January 6th are in week 1 and January 7th to the 13th are in week 2, so if my date was January 10th 2008, my week number would be 2.

An algorithm would be great to get me started and sample code would also help - I'm developing in C++ on Windows.

Related:

Getting week number off a date in MS SQL Server 2005?

解决方案

Pseudocode:

int julian = getDayOfYear(myDate)  // Jan 1 = 1, Jan 2 = 2, etc...
int dow = getDayOfWeek(myDate)     // Sun = 0, Mon = 1, etc...
int dowJan1 = getDayOfWeek("1/1/" + thisYear)   // find out first of year's day
// int badWeekNum = (julian / 7) + 1  // Get our week# (wrong!  Don't use this)
int weekNum = ((julian + 6) / 7)   // probably better.  CHECK THIS LINE. (See comments.)
if (dow < dowJan1)                 // adjust for being after Saturday of week #1
    ++weekNum;
return (weekNum)

To clarify, this algorithm assumes you number your weeks like this:

S  M  T  W  R  F  S
            1  2  3    <-- week #1
4  5  6  7  8  9 10    <-- week #2
[etc.]

getDayOfWeek() and getDayOfYear() are standard date-object operations in most languages. If yours doesn't have them, you can count-forward from some known date (Jan 1, 1970 is a common one), after looking up to see what day of the week it was.

If you're going to implement your own date counting routines, remember that years that are divisible by 100 are NOT leap years, unless they are also divisible by 400. So 1900 was not a leap year, but 2000 was. If you're going to work far back in time, you have to mess with Gregorian vs Julian calendars, etc., see Wikipedia for loads of info on that.

This link talks about date/time functions in Windows/C++ in greater detail.

这篇关于如何计算给定日期的星期数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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