dtmm0148603 2013-09-04 21:33
浏览 180
已采纳

Go-ISO年度周的第一个星期的Unix时间戳

What's a good way of getting the timestamp for, say, the Monday 00:00:00 for the fifth week of 2010? Essentially I'm looking for the inverse function to ISOweek in the time package. I can't seem to find a way to achieve that. Parse() doesn't read week, and simply counting how many "7 days" there have been since the first day of the year/month doesn't really get me what I need.

Thanks a lot in advance! Bill

  • 写回答

4条回答 默认 最新

  • dongzhiqi0332 2013-09-05 09:23
    关注

    I don't see why

    simply counting how many "7 days" there have been since the first day of the year/month doesn't really get me what I need

    Here is my attempt:

    func firstDayOfISOWeek(year int, week int, timezone *time.Location) time.Time {
        date := time.Date(year, 0, 0, 0, 0, 0, 0, timezone)
        isoYear, isoWeek := date.ISOWeek()
        for date.Weekday() != time.Monday { // iterate back to Monday
            date = date.AddDate(0, 0, -1)
            isoYear, isoWeek = date.ISOWeek()
        }
        for isoYear < year { // iterate forward to the first day of the first week
            date = date.AddDate(0, 0, 1)
            isoYear, isoWeek = date.ISOWeek()
        }
        for isoWeek < week { // iterate forward to the first day of the given week
            date = date.AddDate(0, 0, 1)
            isoYear, isoWeek = date.ISOWeek()
        }
        return date
    }
    

    Here is working example with sanity check: http://play.golang.org/p/UVFNFcpaoI

    The code is easy to understand, there is no year/month/day arithmetic, just simple iteration. The runtime complexity is O(n), but given that n is always less than 400 - it's actually not a problem at all.

    It should not have problems with daylight saving, leap years and other tricky date problems if golang date.AddDate is implemented correctly.

    P.S. Funny fact :) First day of week 1 of year 2008 is 2007-12-31. And this is correct, you can check in the calendar.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算