10

I am looking for a method that helps me subtract months from a date in HIVE

I have a date 2015-02-01. Now i need to subtract 2 months from this date so that result should be 2014-12-01.

Can you guys help me out here?

Community
  • 1
  • 1
Vaishak
  • 607
  • 3
  • 8
  • 30
  • 1
    Reading the [Hive Documentation](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF) is always a good place to start. – o-90 Jul 06 '16 at 15:30

3 Answers3

31
 select add_months('2015-02-01',-2);

if you need to go back to first day of the resulting month:

 select add_months(trunc('2015-02-01','MM'),-2);
WillardSolutions
  • 2,316
  • 4
  • 28
  • 38
Manoj R
  • 426
  • 4
  • 4
3

Please try add_months date function and pass -2 as months. Internally add_months uses Java Calendar.add method, which supports adding or subtracting (by passing negative integer).

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

satish
  • 246
  • 2
  • 9
1

--in Hive if the date format is in YYYY-MM-DD format, it becomes really easy to use difference in terms on month and year

from_unixtime(unix_timestamp(2015-02-01,'yyyy-mm-dd')-2*30*24*60*60, 'yyyy-MM-dd');