How to compare two string dates in Java?

后端 未结 8 1314
刺人心
刺人心 2020-12-15 22:41

I have two dates in String format like below -

String startDate = \"2014/09/12 00:00\";

String endDate = \"2014/09/13 00:00\";

I want to

8条回答
  •  隐瞒了意图╮
    2020-12-15 23:32

    Here is a fully working demo. For date formatting, refer - http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Locale;
    
    public class Dating {
    
        public static void main(String[] args) {
    
            String startDate = "2014/09/12 00:00";
            String endDate = "2014/09/13 00:00";
    
            try {
                Date start = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
                        .parse(startDate);
                Date end = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
                        .parse(endDate);
    
                System.out.println(start);
                System.out.println(end);
    
                if (start.compareTo(end) > 0) {
                    System.out.println("start is after end");
                } else if (start.compareTo(end) < 0) {
                    System.out.println("start is before end");
                } else if (start.compareTo(end) == 0) {
                    System.out.println("start is equal to end");
                } else {
                    System.out.println("Something weird happened...");
                }
    
            } catch (ParseException e) {
                e.printStackTrace();
            }
    
        }
    
    }
    

提交回复
热议问题