logo
down
shadow

When using .compareTo to compare dates, why doesn't it take Months into account?


When using .compareTo to compare dates, why doesn't it take Months into account?

By : Geoff
Date : January 12 2021, 07:00 PM
will help you When you format it converts to String. You are formatting and comparing. Hence it is doing String comparison. Hence, the result.
If you want the expected result, you must compare Date objects. I have modified your code to compare both Strings and Dates.
code :
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class CompareDates {
    public static void main(String[] args) throws Exception {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM");
        Calendar cal = Calendar.getInstance();
        Date comDate = new Date();
        cal.add(Calendar.DATE, 8);
        //this adds days to the calender
        comDate = cal.getTime();
        //this applies the edited calender to the date I'm comparing to

        ArrayList<String> arDat = new ArrayList<String>();
        arDat.add("15/08");
        arDat.add("15/09");
        arDat.add("30/08");

        Date redDate = new Date();
        for (int i = 0; i < arDat.size(); i++) {
            Date recDate = formatter.parse(arDat.get(i));
            if (formatter.format(recDate).compareTo(formatter.format(comDate)) < 0) {
                System.out.println("String comparison result: " + recDate);
            }
            if (recDate.compareTo(formatter.parse(formatter.format(comDate))) < 0) {
                System.out.println("Date comparison result: " + recDate);
            }
        }
    }
}
String comparison result: Sat Aug 15 00:00:00 UTC 1970
Date comparison result: Sat Aug 15 00:00:00 UTC 1970
String comparison result: Tue Sep 15 00:00:00 UTC 1970


Share : facebook icon twitter icon
Should I use Calendar.compareTo() to compare dates?

Should I use Calendar.compareTo() to compare dates?


By : Bobby V Adkisson
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Date implements comparable itself so there's no reason to wrap it into calendar:
code :
Calendar someCalendar1 = Calendar.getInstance(); // current date/time
someCalendar1.add(Calendar.DATE, -14);

if (someDate.compareTo(someCalendar1.getTime()) < 0) {
   ...Code...                           
}
if (someDate.before(someCalendar1.getTime())) {
   ...Code...                           
}
DateTime dt = new DateTime().minusWeeks(2);
if (new DateTime(someDate).isBefore(dt)) {
   ...Code...                           
}
Why does daes date1.compareTO(date2)==0 even if dates are the same doesnt give me what i want?

Why does daes date1.compareTO(date2)==0 even if dates are the same doesnt give me what i want?


By : Aleksei Levin
Date : March 29 2020, 07:55 AM
wish of those help I am writing a reminder app that is supposed to have a hashmap (Lebanon in the snippet below) containing different dates as keys and holiday name as value. So this is my calendar: , Set milliseconds in you cal object after setting time.
code :
cal.set(pickerDate.getYear(),
        pickerDate.getMonth(),
        pickerDate.getDayOfMonth(),
        pickerTime.getCurrentHour(),
        pickerTime.getCurrentMinute(),
        0
);
cal.set(Calendar.MILLISECOND,0);
Date date12_1 = format.parse("1/1/2017"); //change this line
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.YEAR, 2014);
cal2.set(Calendar.DAY_OF_YEAR, 1);    
cal2.set(Calendar.MILLISECOND,0);
Date date12_1 = cal2.getTime();
Rails Query - how to compare the months of two dates?

Rails Query - how to compare the months of two dates?


By : SuperCoder
Date : March 29 2020, 07:55 AM
this one helps. I know rails support between query. , I do not know Rails Query, but how about this way?
code :
(start_date between 2017.08.01 and 2017.08.31) or
(end_date between 2017.08.01 and 2017.08.31) or
(start_date < 2017.08.01 and end_date > 2017.08.31)
How to generate dynamic expiry dates like 3 months, 6 months, 9 months and 12 months from the today date in php

How to generate dynamic expiry dates like 3 months, 6 months, 9 months and 12 months from the today date in php


By : Antoine Précigout
Date : March 29 2020, 07:55 AM
I wish this help you You could use the DateTime class and the associated methods available such as add and diff
code :
$interval=new DateInterval('P3M');
$now = new DateTime();
$start=new DateTime();
$end=new DateTime( date( DATE_ATOM, strtotime('+1 year') ) );
$end->add( $interval );


while( $start->add( $interval ) <= $end ){
    echo $diff = $start->diff( $now )->format('%a') . '<br>';
}
92
182
274
366
Compare two dates in Java, without compareTo

Compare two dates in Java, without compareTo


By : Andru Ritman
Date : March 29 2020, 07:55 AM
it helps some times If you are referring to java.util.Date, just do date1.getTime() < date2.getTime(). A simple comparison of long values.
Related Posts Related Posts :
  • Android Broadcastreceiver for other apps install/delete not working
  • Android Studio onClick not working in BindViewHolder
  • How to use Spring Converter for some controllers only?
  • How verify that 3 numbers in sequence are equals?
  • Does the perfomance of "filter then map" and "map then filter" differ in a Stream?
  • How can I set the initial Delay after pressing the start Button to a specific time (HH:mm:ss) format
  • How to switch between Android devices during the tests
  • How to configure java.util.logging via properties to use standard output?
  • How to iterate through array in order
  • Is there better way of iteration to find the evenly divisible number?
  • How to split a string to non empty words if it might include a separator like tab on first place
  • Supplier<Sequence<String>> cannot be iterated more than once
  • Why there is only one thread can actually started in @PostConstruct method?
  • Manage CompletionStage inside of Netty handler
  • Url Problem while Developing on Localhost and deploy on Remote Virtual Server
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • Unable to instantiate default tuplizer Exception
  • Multi-tenant migration to work with quarkus
  • Ignite persisting a Set: Cannot find metadata for object with compact footer
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org