Categories
scala

How to get previous dates using scala

In this post, we will see how to get previous dates using scala.

Scala program – method 1

ZonedDateTime and ZoneId – to get the date and time based on the specific zone id which we prefers to 

DateTimeFormatter – to convert the date and time to a specific format

minusDays function helps us to get the previous dates using scala as below.

import java.time.{ZonedDateTime, ZoneId}
import java.time.format.DateTimeFormatter

object PreviousDate {
  def main(arr: Array[String]): Unit = {
    val previousday = ZonedDateTime.now(ZoneId.of("UTC")).minusDays(1)
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm'Z'")
    val result = formatter format previousday
    println(result)
  }
}
2021-10-01T05:21Z

Scala program – method 2

object YesterdayDate {
  def main(arr: Array[String]): Unit = {
    val today = java.time.LocalDate.now
    val yesterday_date= java.time.LocalDate.now.minusDays(1)
    println(today)
    println(yesterday_date)

  }
}
2021-10-02
2021-10-01

Scala program – method 3

import java.util._
import java.lang._
import java.io._
import java.time.Instant
import java.time.temporal.ChronoUnit


object YesterdayDate {
  def main(arr: Array[String]): Unit = {
    val now = Instant.now
    val yesterday = now.minus(1, ChronoUnit.DAYS)
    System.out.println(now)
    System.out.println(yesterday)
  }
}
2021-10-02T06:37:11.695Z
2021-10-01T06:37:11.695Z

https://github.com/ushanan/SparkFirstProject/blob/master/src/main/scala/com/firstscala/spark/YesterdayDate.scala