周数输入返回疯狂的全周输出 [英] Week number input returns crazy full week output

查看:28
本文介绍了周数输入返回疯狂的全周输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一些关于这些代码有什么问题的反馈.我正在尝试根据周数输出一整周.例如,如果我输入2014/45",我想输出从 11 月 2 日到 11 月 8 日的所有日期.现在我需要弄清楚那一周的第一个日期(因此是 11 月 2 日),然后才能抓住剩下的日子,这就是我把一切搞砸的地方.这是我想出的:

I would like some feedback on what's wrong with these codes. I'm trying to output a full week based on a week number. For instance if I input "2014/45" I would like to output all dates spanning from November 2nd to November 8th. Now I need to figure out the first date in that week (hence November 2nd) before grabbing the rest of the days and this is where everything gets messed up for me. This is what I've come up with:

' getyear = 2014, getweek = 45
Dim DateOfFirstWeekDay As DateTime = GetDateOfFirstDayOfWeek(getyear, getweek)    
Dim FirstDateInSequence As DateTime = CDate(DateAdd("d", _
                        CInt(Abs(Integer.Parse(Weekday(DateOfFirstWeekDay, WeekStartsWith))) * -1) + 1, _
                        DateOfFirstWeekDay)).ToShortDateString()

Protected Friend Shared Function GetDateOfFirstDayOfWeek(ByVal getyear As Nullable(Of Integer), _
                                                 ByVal getweek As Nullable(Of Integer)) As DateTime
    Dim firstWeekDay As DateTime = GetFirstDayOfWeek(newYearDay)

    If getweek = 1 Then
        getweek -= 1
    End If

    Return DateAdd(DateInterval.WeekOfYear, CInt(getweek), firstWeekDay)
End Function

Protected Friend Shared Function GetFirstDayOfWeek(ByVal dt As DateTime) As DateTime
    If dt.DayOfWeek = DayOfWeek.Sunday Then
        Return dt.AddDays(-6)
    Else
        Return dt.AddDays(1 - CInt(dt.DayOfWeek))
    End If
End Function

正如我的问题所暗示的那样,11 月 2 日不是我得到的结果.当我输入 2014/45 时,FirstDateInSequence 返回 2013 年 12 月 22 日.在这里假设某些事情让我失望是很安全的.我只是无法理解它.我想听听你对此的看法.在上面的代码中,我应该把注意力集中在哪里?

As my question implies November 2nd is not the result I get. Instead FirstDateInSequence returns December 22, 2013 when I input 2014/45. It's pretty safe to assume something fails me here. I just can't get my head around it. I'd like your point of view to this. Where should I focus my attention in the code above?

推荐答案

我很难快速遵循您的代码逻辑.所以这是我的.

I'm having a hard time quickly following your code logic. So here's mine.

您可以从查找当年第一周的第一天开始

You could start by finding the first day of the first week of that year

    Dim d As New DateTime(year, 1, 1)

    d = d.AddDays(-d.DayOfWeek)

然后加上天数(week_number -1) * 7

And then add the number of days (week_number -1) * 7

    d = d.AddDays((week_number - 1) * 7)

我做了一个 -1,因为我假设 week_number 将等于 1 以获得第一周.由于 d 已经等于第一周,我们从 0 开始计数.

I do a -1 since I assume that week_number will be equal to 1 to get the first week. Since d is already equal to the first week, we start counting at 0.

要获得最后一天,只需在结果中添加 6(或 7)天

To get the last day, just add 6 (or 7) days to the result

这篇关于周数输入返回疯狂的全周输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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