I have to compare two dates in if/else, the current date and the predefined date (let's say 1 Jan 2011). This was supposed to be simple, but I can't find the way to set the predefined date something like:
Java.util.Date date = new Date("2011-01-01");
How to compare two dates? I really don't know why it's so complicated to do.
We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.
We can convert String to Date in java using parse() method of DateFormat and SimpleDateFormat classes. To learn this concept well, you should visit DateFormat and SimpleDateFormat classes.
You can Convert the date value from String to Date in JavaScript using the `Date()`` class. You can also use parse, which is a static method of the Date class. You can also split the given string date into three parts representing the date, month, and year and then convert it to Date format.
Try:
import java.text.SimpleDateFormat;
import java.util.Date;
...
Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse("2011-01-01");
if(today.equals(predefined)) {
...
}
Use java.util.Calendar
.
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2011);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.DATE, 1);
Date predefined = cal.getTime();
Date now = new Date();
if (now.after(predefined))
{
// do something
}
else
{
// do something else
}
or use JodaTime.
How to compare two dates? I really don't know why it's so complicated to do.
Because calendars/dates/times are really hard to get right, and the Java implementation of Date
(and, in part Calendar
) is an utter train wreck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With