ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Scala program to compare two dates using compareTo() method

Here, we are going to learn how to compare two dates using compareTo() method in Scala programming language?
Submitted by Nidhi, on June 01, 2021

Problem Solution:

Here, we will create objects of the Date class and compare dates using the compareTo() method.

The compareTo() method returns:

  • 0 if both are equal.
  • >0 if the current date object comes after the specified date object.
  • < 0 if the current date object comes before the specified date object.

Program/Source Code:

The source code to demonstrate the compareTo() method of the Date class is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to compare two dates
// using compareTo() method

import java.util.Date;

object Sample {
  def main(args: Array[String]) {
    var date1 = new Date(2021, 5, 10);
    var date2 = new Date(2021, 5, 11);
    var date3 = new Date(2021, 5, 10);

    var result: Int = 0;

    result = date1.compareTo(date2);
    if (result == 0)
      println("date1 and date2 are equal");
    else
      println("date1 and date2 are not equal");

    result = date1.compareTo(date3);
    if (result == 0)
      println("date1 and date3 are equal");
    else
      println("date1 and date3 are not equal");
  }
}

Output:

date1 and date2 are not equal
date1 and date3 are equal

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 three objects of the Date class and compare them using the compareTo() method, and printed the appropriate message on the console screen.

Scala Date & Time Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.