How to compare dates in Java?
How to compare dates in Java?
How to compare dates in Java?
Convert a Date to a String using DateFormat#format method: String pattern = “MM/dd/yyyy HH:mm:ss”; // Create an instance of SimpleDateFormat used for formatting // the string representation of date according to the chosen pattern DateFormat df = new SimpleDateFormat(pattern); // Get the today date using Calendar object. Date today = Calendar.getInstance().getTime(); // Using DateFormat format method we can create a string … Read more
Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By ‘simple’, I mean simpler than this Nope. You did it properly, and as concisely as possible. java.util.Date.from( // Convert from modern java.time class to troublesome old legacy class. DO NOT DO THIS unless you must, to inter operate … Read more
How to get today’s Date?
How to convert currentTimeMillis to a date in Java?
SimpleDateFormat sdf = new SimpleDateFormat(“dd/MM/yyyy”); Calendar c = Calendar.getInstance(); c.setTime(new Date()); // Using today’s date c.add(Calendar.DATE, 5); // Adding 5 days String output = sdf.format(c.getTime()); System.out.println(output);
If you want to convert an Instant to a Date: Date myDate = Date.from(instant); And then you can use SimpleDateFormat for the formatting part of your question: SimpleDateFormat formatter = new SimpleDateFormat(“dd MM yyyy HH:mm:ss”); String formattedDate = formatter.format(myDate);
Since Date implements Comparable, it has a compareTo method just like String does. So your custom Comparator could look like this: public class CustomComparator implements Comparator<MyObject> { @Override public int compare(MyObject o1, MyObject o2) { return o1.getStartDate().compareTo(o2.getStartDate()); } } The compare() method must return an int, so you couldn’t directly return a boolean like you were planning to anyway. Your sorting code would be just about like you wrote: … Read more
Set Date in a single line