Here, we will read the number of days from the user. Then we will create a date object and add the input number of days to created date object. After that, we will print the updated date on the console screen.
The source code to add days to the current date is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
// Scala program to add days into current 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 days: Int = 0;
print("Enter number of days: ");
days = scala.io.StdIn.readInt();
var newDate = new Date(date.getTime() + (MILLIS_IN_A_DAY * days));
println("Current date: \n" + date);
println("New date: \n" + newDate);
}
}
Output:
Enter number of days: 10
Current date:
Mon May 31 02:18:59 GMT 2021
New date:
Thu Jun 10 02:18:59 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 and read the number of days from the user.
After that, we added days to the date object and created a new object that contains an updated date using the below statement.
var newDate = new Date(date.getTime()+(MILLIS_IN_A_DAY*days));
At last, we printed both objects on the console screen.
Program/Source Code:
The source code to add days to the current date is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.
Output:
Explanation:
Here, we used an object-oriented approach to create the program. And, we imported the Date class using the below statement,
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 and read the number of days from the user.
After that, we added days to the date object and created a new object that contains an updated date using the below statement.
At last, we printed both objects on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer