I am trying to compare a date in a String format to the current date. This is how I did it (haven't tested, but should work), but am using deprecated methods. Any good suggestion for an alternative? Thanks.
P.S. I really hate doing Date stuff in Java. There are so many ways to do the same thing, that you really aren't sure which one is the correct one, hence my question here.
String valid_until = "1/1/1990";
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Date strDate = sdf.parse(valid_until);
int year = strDate.getYear(); // this is deprecated
int month = strDate.getMonth() // this is deprecated
int day = strDate.getDay(); // this is deprecated
Calendar validDate = Calendar.getInstance();
validDate.set(year, month, day);
Calendar currentDate = Calendar.getInstance();
if (currentDate.after(validDate)) {
catalog_outdated = 1;
}
You could try this
Calendar today = Calendar.getInstance ();
today.add(Calendar.DAY_OF_YEAR, 0);
today.set(Calendar.HOUR_OF_DAY, hrs);
today.set(Calendar.MINUTE, mins );
today.set(Calendar.SECOND, 0);
and you could use today.getTime()
to retrieve value and compare.
You can use compareTo()
CompareTo method must return negative number if current object is less than other object, positive number if current object is greater than other object and zero if both objects are equal to each other.
// Get Current Date Time
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm aa");
String getCurrentDateTime = sdf.format(c.getTime());
String getMyTime="05/19/2016 09:45 PM ";
Log.d("getCurrentDateTime",getCurrentDateTime);
// getCurrentDateTime: 05/23/2016 18:49 PM
if (getCurrentDateTime.compareTo(getMyTime) < 0)
{
}
else
{
Log.d("Return","getMyTime older than getCurrentDateTime ");
}
String date = "03/26/2012 11:00:00";
String dateafter = "03/26/2012 11:59:00";
SimpleDateFormat dateFormat = new SimpleDateFormat(
"MM/dd/yyyy hh:mm:ss");
Date convertedDate = new Date();
Date convertedDate2 = new Date();
try {
convertedDate = dateFormat.parse(date);
convertedDate2 = dateFormat.parse(dateafter);
if (convertedDate2.after(convertedDate)) {
txtView.setText("true");
} else {
txtView.setText("false");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
it return true.. and you can also check before and equal with help of date.before and date.equal..
Kotlin supports operators overloading
In Kotlin you can easily compare dates with compare operators. Because Kotlin already support operators overloading. So to compare date objects :
firstDate: Date = // your first date
secondDate: Date = // your second date
if(firstDate < secondDate){
// fist date is before second date
}
and if you're using calendar objects, you can easily compare like this:
if(cal1.time < cal2.time){
// cal1 date is before cal2 date
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.getDefault());
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
Date date1 = dateFormat.parse("2013-01-01");
Date date2 = dateFormat.parse("2013-01-02");
calendar1.setTime(date1);
calendar2.setTime(date2);
System.out.println("Compare Result : " + calendar2.compareTo(calendar1));
System.out.println("Compare Result : " + calendar1.compareTo(calendar2));
Compares the time represented by this Calendar to that represented by the given Calendar.
Returns 0 if the times of the two Calendars are equal, -1 if the time of this Calendar is before the other one, 1 if the time of this Calendar is after the other one.
Calendar toDayCalendar = Calendar.getInstance();
Date date1 = toDayCalendar.getTime();
Calendar tomorrowCalendar = Calendar.getInstance();
tomorrowCalendar.add(Calendar.DAY_OF_MONTH,1);
Date date2 = tomorrowCalendar.getTime();
// date1 is a present date and date2 is tomorrow date
if ( date1.compareTo(date2) < 0 ) {
// 0 comes when two date are same,
// 1 comes when date1 is higher then date2
// -1 comes when date1 is lower then date2
}
Note that the right format is ("dd/MM/yyyy") before the code works. "mm" means minuts !
String valid_until = "01/07/2013";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = null;
try {
strDate = sdf.parse(valid_until);
} catch (ParseException e) {
e.printStackTrace();
}
if (new Date().after(strDate)) {
catalog_outdated = 1;
}
You can use validDate.setTime(strDate) Have a look at the javadoc at http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html
Time for the modern answer.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("d/M/u");
String validUntil = "1/1/1990";
LocalDate validDate = LocalDate.parse(validUntil, dateFormatter);
LocalDate currentDate = LocalDate.now(ZoneId.of("Pacific/Efate"));
if (currentDate.isAfter(validDate)) {
System.out.println("Catalog is outdated");
}
When I ran this code just now, the output was:
Catalog is outdated
Since it is never the same date in all times zones, give explicit time zone to LocalDate.now
. If you want the catalog to expire at the same time in all time zones, you may give ZoneOffset.UTC
as long as you inform you users that you are using UTC.
I am using java.time, the modern Java date and time API. The date-time classes that you used, Calendar
, SimpleDateFormat
and Date
, are all poorly designed and fortunately long outdated. Also despite the name a Date
doesn’t represent a date, but a point in time. One consequence of this is: even though today is February 15, 2019, a newly created Date
object is already after (so not equal to) a Date
object from parsing 15/02/2019
. This confuses some. Contrary to this the modern LocalDate
is a date without time of day (and without time zone), so two LocalDate
s representing today’s date will always be equal.
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).You can directly create a Calendar
from a Date
:
Calendar validDate = new GregorianCalendar();
validDate.setTime(strDate);
if (Calendar.getInstance().after(validDate)) {
catalog_outdated = 1;
}
Update: The Joda-Time library is now in maintenance-mode, and recommends migrating to the java.time framework that succeeds it. See the Answer by Ole V.V..
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.
If you want date-only without time-of-day, then use the LocalDate class.
Getting the current date depends on the time zone. A new date rolls over in Paris before Montréal. Specify the desired time zone rather than depend on the JVM's default.
Example in Joda-Time 2.3.
DateTimeFormat formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( "1/1/1990" );
boolean outdated = LocalDate.now( DateTimeZone.UTC ).isAfter( localDate );
SimpleDateFormat sdf=new SimpleDateFormat("d/MM/yyyy");
Date date=null;
Date date1=null;
try {
date=sdf.parse(startDate);
date1=sdf.parse(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
if (date1.after(date) && date1.equals(date)) {
//..do your work..//
}
Sometimes we need to do a list with dates, like
today with hour
yesterday with yesterday
other days with 23/06/2017
To make this we need to compare current time with our data.
Public class DateUtil {
Public static int getDateDayOfMonth (Date date) {
Calendar calendar = Calendar.getInstance ();
Calendar.setTime (date);
Return calendar.get (Calendar.DAY_OF_MONTH);
}
Public static int getCurrentDayOfMonth () {
Calendar calendar = Calendar.getInstance ();
Return calendar.get (Calendar.DAY_OF_MONTH);
}
Public static String convertMillisSecondsToHourString (long millisSecond) {
Date date = new Date (millisSecond);
Format formatter = new SimpleDateFormat ("HH: mm");
Return formatter.format (date);
}
Public static String convertMillisSecondsToDateString (long millisSecond) {
Date date = new Date (millisSecond);
Format formatter = new SimpleDateFormat ("dd / MM / yyyy");
Return formatter.format (date);
}
Public static long convertToMillisSecond (Date date) {
Return date.getTime ();
}
Public static String compare (String stringData, String yesterday) {
String result = "";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss");
Date date = null;
Try {
Date = simpleDateFormat.parse (stringData);
} Catch (ParseException e) {
E.printStackTrace ();
}
Long millisSecond = convertToMillisSecond (date);
Long currencyMillisSecond = System.currentTimeMillis ();
If (currencyMillisSecond> millisSecond) {
Long diff = currencyMillisSecond - millisSecond;
Long day = 86400000L;
If (diff <day && getCurrentDayOfMonth () == getDateDayOfMonth (date)) {
Result = convertMillisSecondsToHourString (millisSecond);
} Else if (diff <(day * 2) && getCurrentDayOfMonth () -1 == getDateDayOfMonth (date)) {
Result = yesterday;
} Else {
Result = convertMillisSecondsToDateString (millisSecond);
}
}
Return result;
}
}
convert the date to Calendar and make your calculations there. :)
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.geT(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH); //same as cal.get(Calendar.DATE)
Or:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date strDate = sdf.parse(valid_until);
if (strDate.after(new Date()) {
catalog_outdated = 1;
}
Source: Stackoverflow.com