Compare current date with date from property file - java

I am getting a hard coded date from the property file , which is of the format dd-MMM-yyyy.
Now i need to compare it with current date of same format. For that purpose , i cooked up this piece of code :
Date convDate = new Date();
Date currentFormattedDate = new Date();
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
convDate = new SimpleDateFormat("dd-MMM-yyyy").parse("20-Aug-2013");
currentFormattedDate = new Date(dateFormat.format(currentFormattedDate));
if(currentFormattedDate.after(convDate) || currentFormattedDate.equals(convDate)){
System.out.println("Correct");
}else{
System.out.println("In correct");
}
But eclipse tells me that new Date has been depreciated. Does any one know of any alternative way of doing this ? I am going crazy over this. Thanks !

One of the way is to use the Calendar class and its after() , equals() and before() methods.
Calendar currentDate = Calendar.getInstance();
Calendar anotherDate = Calendar.getInstance();
Date convDate = new SimpleDateFormat("dd-MMM-yyyy").parse("20-Aug-2013");
anotherDate.setTime(convDate);
if(currentDate .after(anotherDate) ||
currentDate .equals(anotherDate)){
System.out.println("Correct");
}else{
System.out.println("In correct");
}
You can also use Jodatime library , see this SO answer.

You should use the Date(long) constructor:
Date convDate = new Date(System.currentTimeMillis());
This way you'll avoid the deprecation warning and will get a Date instance with the system time.

Date represents number of milliseconds since the epoch. Why not just use the Date returned from
Date currentFormattedDate = new Date();
?

Related

How can i enter current date and time in textbox

I want to enter the current date and time along with second in a text box ; How can I do that ?
The code what I have written is as below , but it is only entering the string value what I am passing in send keys , which is clearly indicating I am not in correct track .
Any suggestion ?
// Create object of SimpleDateFormat class and decide the format
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy ");
//get current date time with Date()
Date date = new Date();
// Now format the date
String date1= dateFormat.format(date);
// Print the Date
System.out.println(date1);
collection_title.sendKeys("date1");
In collection_title.sendKeys("date1"); you are not using your variable date1, you are using the String "date1" - there should be no quotes around date1.
It should work like this:
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = new Date();
collection_title.sendKeys(dateFormat.format(date));
Maybe you should try to use LocalDateTime.now() or Calender.getInstance() instead of new Date(), because the Date API methods are flawed and deprecated.

How to do subtraction from a particular date using Java [duplicate]

This question already has answers here:
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 4 years ago.
I am encountering an issue which is related to Java Date Function.
I'm getting the date from Application (example: 6/5/18) which is in MM/DD/YY format. Now I need to do -2 from the date. I know how to do -2 from current system date using calendar object (see the below code).
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
I'm not able to put the date which I'm getting from Application in this format. Can someone please help me? (Any other way to do it would also be fine)
I suggest you to use Java 8 compatible Date and Time types.
If you use java.time.LocalDate then this is the solution:
LocalDate.now().minusDays(2)
From your question, it seems that you have the challenge in dealing with formatting, and then doing the subtraction.
I would recommend Java Date and Time Apis for this purpose, using a formatter.
A junit method to achieve your requirement is given below
#Test
public void testDateFormatUsingJava8() {
CharSequence inputdateTxt = "6/5/18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate inputDate = LocalDate.parse(inputdateTxt, formatter);
System.out.println(inputDate.minusDays(2L).format(formatter));
}
#Test
public void testDateCalenderUsingStringSplit() {
String inputdateTxt = "6/5/18";
String[] dateComponenets = inputdateTxt.split("//");
Calendar cal = Calendar.getInstance();
//Know where are the year month and date are stored.
cal.set(Integer.parseInt(dateComponenets[2]), Integer.parseInt(dateComponenets[0]), Integer.parseInt(dateComponenets[2]) );
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
}
#Test
public void testDateCalenderUsingJavaUtilDateApi() throws ParseException {
String inputdateTxt = "6/5/18";
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
Date date = dateFormat.parse(inputdateTxt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE,-2);
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
The reason why I use "M/d/yy" is because your question does not pad the date and month fields in the input date with a zero. If there is a guarantee that you receive a padded value in the date and month field, using "MM/dd/yy" is suggested.
See the following answer for your reference :
DateTimeFormatterSupport for Single Digit Values
EDIT: considering the limitation to not use Java 8 Date Time APIs, I have added two other alternatives to solve the problem. The OP is free to choose any one of the solutions. Kept the Java 8 solution intact for information purposes.
Calendar cal = Calendar.getInstance();
cal.set(2018, 5, 6); // add this, setting data from the value you parsed
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ PastDate);

How to subtract X day from a Date object in Java?

I want to do something like:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
How to do it?
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
#JigarJoshi it's the good answer, and of course also #Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime is org.joda.time.DateTime;
Date is java.util.Date
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
You may also be able to use the Duration class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}

Date comparison in android

I'm facing some problems in comparing the current date and the date which is retrieved from Database.I just retrieved date from DataBase and Stored in a Date variable like this
String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));
SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = currentFormater.parse(due_date_task);
Now,what i want is should check whether date which is retrieved from DataBase is Equivalent to CurrentDate or not.
Calendar currentDate = Calendar.getInstance();
Date date2 = currentDate.getTime();
if(date1.equals(date2))
System.out.println("Today Task");
i just want to check like this.Thanks in advance
For exact match including milliseconds, use getTime:
if(date.getTime() == date1.getTime()){
//do something
}
You can use this function:
private boolean compareDates(Calendar objCal1, Calendar objCal2) {
return ((objCal1.get(Calendar.YEAR) == objCal2.get(Calendar.YEAR))
&& (objCal1.get(Calendar.DAY_OF_YEAR) == objCal2.get(Calendar.DAY_OF_YEAR)));
}
creating the calendar objects:
Calendar objCal1 = new GregorianCalendar().setTime(date);
Calendar objCal2 = new GregorianCalendar().setTime(date1);
Try this way to get the current date,
Calendar calCurr = Calendar.getInstance();
Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis()); // see what it gives? dont know why?
Date date = new Date();
calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());// so added one month to it
Log.i("Time in mili of Current - after update", ""+calCurr.getTimeInMillis()); // now get correct
now create Calendar object for database value,
String due_date_task = cursor.getString(cursor.getColumnIndex(dueDateOfTask));
SimpleDateFormat currentFormater = new SimpleDateFormat("dd/MM/yyyy");
Date date = currentFormater.parse(due_date_task);
Calendar start = Calendar.getInstance();
start.set(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
and now Compare both the Calendar objects
if(calCurr.equals(start))

How to get a comparable date parsing "13:00"?

I was trying with:
new Date("13:00")
All I care about is the time of day and that when compared new Date("12:00") is less than new Date("13:00"). Is there no library for that?
If you create two Dates and set only the hours and minutes (e.g. by parsing with a time format pattern or by setting fields in a Calendar) you can compare them.
java.util.Date provides before and after methods for date comparison. It also implements Comparable#compareTo, so you can test for before/equals/after in one invocation.
// get dates using format/parse
DateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = format.parse("13:00");
Date date2 = format.parse("13:00");
// use Date comparison methods
boolean before = date1.before(date2);
System.err.println(before);
// use compareTo
int compare = date1.compareTo(date2);
System.err.println(compare);
// get dates using Calendar
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 12);
calendar.set(Calendar.MINUTE, 0);
date1 = calendar.getTime();
calendar.set(Calendar.HOUR, 13);
date2 = calendar.getTime();
If the times are in "HH:mm" format you can just compare the strings.
String time1 = "12:00";
String time2 = "13:00";
int compared = time1.compareTo(time2); // compared == -1
JodaTime is very popular in Java. Take a look at LocalTime.

Categories