Kontext Kontext / Code Snippets & Tips

Spark SQL - Add Day, Month and Year to Date

event 2022-06-14 visibility 9,247 comment 0 insights toc
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);

Subtract days

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

Add months

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

Substract months

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

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);
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