javadatetime-comparison

not able to catch particular time slot in java


I was working in some project, in which it was required to test the particular time if between 08 PM to 12 AM time slot. I converted the dates to long and check the difference. For all other time slots I was getting positive output. But when I tested for 08 PM to 12 AM I got no output. below is my code:

package com.google.pulldata.utils;
import java.text.SimpleDateFormat;
public class Test2 {

    public static void main(String[] args) throws Exception{

        try {
            process1();
            process2();
        }catch(Exception ex) {
            ex.printStackTrace();
        }

    }

    private static void process1() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_hh_a");


        String dateRange1="2018_11_18_04_PM";
        String dateRange2="2018_11_18_08_PM";


        long dtRange1=sdf.parse(dateRange1).getTime();
        long dtRange2=sdf.parse(dateRange2).getTime();

        String dateTest = "2018_11_18_06_PM";
        long dtTest=sdf.parse(dateTest).getTime();


        if(dtTest>=dtRange1 && dtTest<=dtRange2) {
            System.out.println("yes time is between 04 PM to 08 PM slot");
        }
    }



    private static void process2() throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_hh_a");


        String dateRange1="2018_11_18_08_PM";
        String dateRange2="2018_11_18_12_AM";


        long dtRange1=sdf.parse(dateRange1).getTime();
        long dtRange2=sdf.parse(dateRange2).getTime();

        String dateTest = "2018_11_18_10_PM";
        long dtTest=sdf.parse(dateTest).getTime();


        if(dtTest>=dtRange1 && dtTest<=dtRange2) {
            System.out.println("yes time is between 08 PM to 12 AM slot");
        }
    }
}

output:

yes time is between 04 PM to 08 PM slot

as you can see, I am getting output for process1() method but not for 'proccess2()`. can anyone help me out why is it happening?


Solution

  • Because 2018_11_18_10_PM comes after 2018_11_18_12_AM.