美文网首页
hive 获取自然周

hive 获取自然周

作者: c934 | 来源:发表于2020-04-22 09:58 被阅读0次
    1. 选择一个周一的相对日期 比如 2018-01-01 是周一
    2. 假如当前时间是 p0,那查询当前时间的自然周的周一日期
    
    select  date_sub({p0},pmod(datediff({p0}, '2018-01-01'), 7))
    
    
    select date_sub('2020-04-15',pmod(datediff('2020-04-15','2018-01-01'),7))  
    -- 输出结果为  2020-04-13
    

    跨年自然周的处理

    现象:

    查询当前日期是这一年的第几周 可以使用如下方法

    select weekofyear(Fcurrent)
    select date_format(Fcurrent,'yyyyww')
    -- 比如 
    select weekofyear('2020-04-01')   -- 输出 14
    select date_format('2020-04-01','yyyyww') -- 输出202014 代表2020年的第14周
    -- 但是如果时间是跨年的情况 比如
    select weekofyear('2019-12-30')  -- 输出 1
    select date_format('2019-12-30','yyyyww') -- 输出 201901
    

    原因:

    具体解释 如链接 [mysql跨年处理](http://week-number.net/calendar-with-week-numbers-2019.html](http://week-number.net/calendar-with-week-numbers-2019.html)

    在java 中使用Calendar 处理周的时候也有这种情况,一年的第一周 的设置有如下参数

    calendar.setFirstDayOfWeek(Calendar.MONDAY); -- 默认周一为一周的开始时间
    calendar.setMinimalDaysInFirstWeek(4); --第一周的最小天数必须是4天以上
    

    处理

    想要得到正确的结果

    select year(date_sub(next_day(date_sub(current_date,1),'MO'),4))*100+weekofyear(date_sub(current_date,1));
    
    --- next_day('时间','下周几')
    

    备注 hive 函数大全 (https://www.cnblogs.com/MOBIN/p/5618747.html

    相关文章

      网友评论

          本文标题:hive 获取自然周

          本文链接:https://www.haomeiwen.com/subject/naybihtx.html