0

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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
J. Doe
  • 69
  • 7
  • 6
    What sort of date would you expect to occur after 8pm, but before midnight on the same day? Midnight is the beginning of the day, not the end. In other words, 10pm is AFTER 12am; and so is every other moment of the day. You might like to try `dateRange2="2018_11_19_12_AM";` - that is, midnight of the NEXT day. – Dawood ibn Kareem Dec 14 '18 at 05:41
  • @DawoodibnKareem make that an answer so that i can +1 it – Maurice Perry Dec 14 '18 at 05:49
  • I recommend you avoid the `SimpleDateFormat` class. It is not only long outdated, it is also notoriously troublesome. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 14 '18 at 12:18

1 Answers1

1

Because 2018_11_18_10_PM comes after 2018_11_18_12_AM.

Mani
  • 508
  • 1
  • 7
  • 18