JetBrains Academy: LocalTime - Kamil-Jankowski/Learning-JAVA GitHub Wiki
JetBrains Academy: LocalTime
Seconds since start of a day:
Write a program that reads a number of seconds from the start of a day and prints the current time.
If the resulting time has zero seconds, do not output them.
import java.util.Scanner;
import java.time.LocalTime;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int seconds = Integer.parseInt(scanner.nextLine());
LocalTime time = LocalTime.ofSecondOfDay(seconds);
System.out.println(time);
}
}
Some hours and minutes ago:
Write a program that reads a point in time and prints another point in time at the specified number of hours and minutes before the given one.
Input data format The first line contains a point in time in hours:minutes format. The second line contains two numbers: hours and minutes separated by a space.
Output data format The single output line should contain a point in time before the input time in the same format.
import java.util.Scanner;
import java.time.LocalTime;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
LocalTime time = LocalTime.parse(scanner.nextLine());
String[] parameters = scanner.nextLine().split("\\s+");
int h = Integer.parseInt(parameters[0]);
int m = Integer.parseInt(parameters[1]);
LocalTime timeBefore = time.minusHours(h).minusMinutes(m);
System.out.println(timeBefore);
}
}
Seconds between two time points:
Implement a method that takes two instances of LocalTime
and determines how many seconds are between them.
import java.time.LocalTime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int time1 = LocalTime.parse(scanner.nextLine()).toSecondOfDay();
int time2 = LocalTime.parse(scanner.nextLine()).toSecondOfDay();
int difference = Math.abs(time1 - time2);
System.out.println(difference);
}
}
Return time without seconds:
Write a program that reads a point in time and outputs the same time without seconds.
import java.util.Scanner;
import java.time.LocalTime;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
LocalTime time = LocalTime.parse(scanner.nextLine()).withSecond(0);
System.out.println(time);
}
}