Convert java.util.Date to String

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

LocalDate to java.util.Date and vice versa simplest conversion?

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

Adding days 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);

Sort ArrayList of custom Objects by property

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