简体   繁体   中英

How to calculate certain date using month in Hive

Is there any way to set certain date in the past, using current date in Hive? I need to get always first day of previous month at any moment in current month and then using it for filtration

Use add_month to get previous month date, use TRUNC to get first day:

select trunc(add_months(current_date,-1),'MM') --returns 2021-06-01 for current_date = 2021-07-22

If you do not have TRUNC function, then use add_month to get previous month date, use substr to get 'yyyy-MM', concatenate with '-01' to get first day of month:

select concat(substr(add_months(current_date,-1),1,7),'-01') --returns 2021-06-01 for current_date = 2021-07-22

Also you can subtract 2 months, get last_day() and add one day to get previous month first day:

select date_add(last_day(add_months(current_date, -2)),1) --returns 2021-06-01 for current_date = 2021-07-22

And one more simple method:

select date_format(add_months(current_date, -1),'yyyy-MM-01') 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM