How to compare two times in Java 8 and Older version

Do you need to compare two times in java? If you are using Java 8 then it eases your job. In this tutorial, let us see that how to compare two times in Java 8 and in older version of java. The below example will accept two times (start time & end time) as input string and compare whether the start time is greater than or less than or equal to the end time.

package net.javaonline;

import java.sql.Time;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;

public class CompareTime {

	public static void main(String args[]) {

	

		String startTimeStr = JOptionPane
				.showInputDialog("Enter Start time: (HH:MM:SS)"); // Getting
																	// start
																	// time

		String endTimeStr = JOptionPane
				.showInputDialog("Enter End time: (HH:MM:SS)"); // Getting end
																// time

		// String startTimeStr ="09" + ":" + "59" + ":"+ "30";
		// String endTimeStr = "09" + ":" + "31" + ":"+ "30";

		compareTimeJava8(startTimeStr, endTimeStr);

		compareTime(startTimeStr, endTimeStr);

	}
	
	//Using Java8

	public static void compareTimeJava8(String startTimeStr, String endTimeStr) {

		LocalDate today = LocalDate.now();
		String startTimeStrT = today + " " + startTimeStr;
		String endTimeStrT = today + " " + endTimeStr;

		DateTimeFormatter formatter = DateTimeFormatter
				.ofPattern("yyyy-MM-dd HH:mm:ss");

		try {

			LocalDateTime startTime = LocalDateTime.parse(startTimeStrT,
					formatter);
			LocalDateTime endTime = LocalDateTime.parse(endTimeStrT, formatter);

			Duration d = Duration.between(startTime, endTime);

			System.out.println("dur " + d.getSeconds());
			if (d.getSeconds() == 0)
				System.out.println("Both Start time and End Time are equal");
			else if (d.getSeconds() > 0)
				System.out.println("Start time is less than end time");
			else
				System.out.println("Start time is greater than end time");

		} catch (DateTimeParseException e) {
			System.out.println("Invalid Input" + e.getMessage());

		}

	}
	
	
	
	
	//Using Java Older version

	public static void compareTime(String startTimeStr, String endTimeStr) {

		Pattern p = Pattern.compile("^([0-2][0-3]):([0-5][0-9]):([0-5][0-9])$"); //Regex is used to validate time format (HH:MM:SS)

		int hhS = 0;
		int mmS = 0;
		int ssS = 0;
		
		int hhE = 0;
		int mmE = 0;
		int ssE = 0;

		Matcher m = null;

		m = p.matcher(startTimeStr);
		if (m.matches()) {
			String hhStr = m.group(1);
			String mmStr = m.group(2);
			String ssStr = m.group(3);

			hhS = Integer.parseInt(hhStr);
			mmS = Integer.parseInt(mmStr);
			ssS = Integer.parseInt(ssStr);

		}

		else {
			System.out.println("Invalid start time");
			System.exit(0);

		}

	

		m = p.matcher(endTimeStr);
		if (m.matches()) {
			String hhStr = m.group(1);
			String mmStr = m.group(2);
			String ssStr = m.group(3);

			hhE = Integer.parseInt(hhStr);
			mmE = Integer.parseInt(mmStr);
			ssE = Integer.parseInt(ssStr);

		}

		else {
			System.out.println("Invalid End time");
			System.exit(0);

		}

		

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, hhS); // Start hour
		cal.set(Calendar.MINUTE, mmS); // Start Mintue
		cal.set(Calendar.SECOND, ssS); // Start second

		Time startTime = new Time(cal.getTime().getTime());
		// System.out.println("your time: "+sqlTime3);

		cal.set(Calendar.HOUR_OF_DAY, hhE); // End hour
		cal.set(Calendar.MINUTE, mmE); // End Mintue
		cal.set(Calendar.SECOND, ssE); // End second

		Time endTime = new Time(cal.getTime().getTime());

		if (startTime.equals(endTime)) {
			System.out.println("Both Start time and End Time are equal");
		} else if (startTime.before(endTime)) {
			System.out.println("Start time is less than end time");
		}

		else
			System.out.println("Start time is greater than end time");

	}

}

 

Reference: Java 8 Date

Leave a Reply

penis large medicine black mamba sex enhancement pills that make your pinus grow which pill is best for erectile dysfunction 5 hour forced male enhancement where to buy prolong male enhancement rhino male enhancement ingredients male enhancement pills sold in gas stations articles longinexx male enhancement exten plus 2100 male enhancement hot rod male enhancement buy at strore triple delight male enhancement premium gold male enhancement safe male enhancement pills taoist penis enlargement bool black mamba male enhancer pills that make you stay hard longer black ant king pills reviews pink like a pill viagra cost per pill costco blue and white capsule pills bigger dick pill extenze 4 day pill red hard male enhancement pill orange pill no markings sex pills porstars use magnum gold male enhancement formula 41 extreme male enhancement green circle pill best price no prescription ed pills elite dangerous tablet ed drugs otc penis enlargement pills does not work tadalafil tablets 40mg steve harvey vitality male enhancement pills viagra tablet use where to get male enhancement pills online which otc pills woek for erection

green roads cbd oil cbd trade shows 2020 cbd pennsylvania can cbd oil make you feel speedy shelf life of cbd oil cbd oil jefferson city mo just chill cbd oil cbd antipsychotic cbd oil legal in tn cbd oil massage benefits medix cbd oil review who invented cbd oil green roads cbd stock symbol abcann cbd oil cbd for cerebral palsy cbd oil bulk wholesale cbd oil bronchitis advanced cbd oil with terpenes best topical cbd for pain cbd oil extract cbd and paranoia map of the melbourne cbd cbd oil thailand how does cbd work cbd crystallization is vaping cbd oil bad for you ethanol extracted cbd your cbd store covington op shop sydney cbd cbd oil for anxiety dosage who owns cbdmd mark 3 cbd oil medix cbd oil dosage everyday advanced cbd oil cbd hemp oil and macular degeneration kangaroo cbd oil is cbd oil taken at bedtime cbd oil and dialysis

xenadrine weight loss pills boost weight loss pills pill to lose weight easy and popular weight loss diet best workout supplements for weight loss weight loss cookies diet chocolate recipes for keto diet best type of diet to lose weight how much weight can i lose on a ketogenic diet dr nows weight loss diet diet for a positive blood type to lose weight weird diets for weight loss what diet is the best to lose weight fast weight loss pills garcinia cambogia walgreens meridia weight loss medicine how do you take thyroid pill to lose weight weight loss medicines available in india adhd medicine that helps with weight loss what foods are on the keto diet keto diet recipes delivered beginning keto diet meal plan health hut best weight loss pills high carb low fat vegan diet weight loss side effects of water pills for weight loss water pills loss weight dollar tree why does alcohol stop weight loss on atkins diet kosher diet for weight loss best weight loss pills for thighs weight loss heart healthy diet tuna diets weight loss bounce elimination diet weight loss what to eat on keto diet pills healing fats diet for weight loss new weight loss drug garcinia cambogia what is the best diet for fastest weight loss medicine for weight loss usa lose weight after birth control pills new weight loss pill fda approved