Scala program to print yesterday's date

Here, we are going to learn how to print yesterday's date in Scala programming language?
Submitted by Nidhi, on May 31, 2021 [Last updated : March 11, 2023]

Scala - Printing Yesterday's Date

Here, we will create an object of Date class and print today's and yesterday's date on the console screen.

Scala code to print yesterday's date

The source code to print yesterday's date is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to print yesterday's date

import java.util.Date;

object Sample {
  def main(args: Array[String]) {
    var MILLIS_IN_A_DAY = 1000 * 60 * 60 * 24;
    var date = new Date();
    var previousDate = new Date(date.getTime() - MILLIS_IN_A_DAY);

    println("Today's date: \n" + date);
    println("Yesterday's date: \n" + previousDate);
  }
}

Output

Today's date: 
Mon May 31 02:08:37 GMT 2021
Yesterday's date: 
Sun May 30 02:08:37 GMT 2021

Explanation

Here, we used an object-oriented approach to create the program. And, we imported the Date class using the below statement,

import java.util.Date;

Then we created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we created a variable MILLIS_IN_A_DAY, which contains milliseconds in a day. Then we created an object date of the Date class.

After that, we subtracted milliseconds from the date object and created a new object that contains the date of the previous day using the below statement.

var nextDate = new Date(date.getTime()-MILLIS_IN_A_DAY);

At last, we printed both objects on the console screen.

Scala Date & Time Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.