Kontext Kontext

Spark SQL - Add Day, Month and Year to Date

event 2022-06-14 visibility 8,540 comment 0 insights toc
more_vert
insights Stats
Spark SQL provides quite a few functions we can use to add days, months or years to a date or timestamp. These functions include date_add, date_sub, add_months, etc. These functions can also be used to subtract days, months or years from a date.

The following are the examples.

Add days

spark-sql> select date_add(DATE'2022-06-01', 1);
2022-06-02

Subtract days

spark-sql> select date_add(DATE'2022-06-01', -1);
2022-05-31
spark-sql> select date_sub(DATE'2022-06-01', 2);
2022-05-30

Add months

spark-sql> select add_months(DATE'2022-06-01',1);
2022-07-01

Substract months

spark-sql> select add_months(DATE'2022-06-01',-2);
2022-04-01

Add years

There is no direct function we can use but we can use add_months. For example, adding one year is equivalent to add 12 months.

spark-sql> select add_months(DATE'2022-06-01',12) as add_one_year, add_months(DATE'2022-06-01',24) as add_two_years;
2023-06-01      2024-06-01

Subtract years

spark-sql> select add_months(DATE'2022-06-01',-12);
2021-06-01
More from Kontext
comment Comments
No comments yet.

Please log in or register to comment.

account_circle Log in person_add Register

Log in with external accounts