Add and subtract days from a timestamp in Java / Scala

The following function adds the days indicated in the days argument (positive or negative integer value) to the timestamp passed through the date argument. The function expects the timestamp input format indicated in the inputFormat argument and returns the new timestamp resulting from the addition or subtraction with the format indicated in the outputFormat argument (format example: “yyyyMMdd”).

def dateAddDay(date: String, days: Int, inputFormat: String, outputFormat: String) : String = {
  val dateAux = Calendar.getInstance()
  dateAux.setTime(new SimpleDateFormat(inputFormat).parse(date))
  dateAux.add(Calendar.DATE, days)
  return new SimpleDateFormat(outputFormat).format(dateAux.getTime())

Don’t forget to import the following classes:

import java.text.SimpleDateFormat
import java.util.Calendar

Leave a Reply

Your email address will not be published. Required fields are marked *