string - Comparing dates in Java -


i read date functions cant think best way solve problem.

i have couple of dates database string , want compare may current date. using compareto, there problem using function guess because of comparing strings.

this function:

public int datecompare(string today, string date2){     return today.compareto(date2); } 

and when use in sample dates:

datecompare("04/19/2013","04/18/2013"); 

it returns 1, , when change value of first parameter "04/20/2013" still returns 1.

please help...

java has date object. should using instead.

import java.util.calendar; import java.util.date;  public class comparedates {      public static void main(string[] args) {         // create calendar, default today         calendar cal = calendar.getinstance();         // subtract 1 day         cal.add(calendar.date, -1);         // compare result (1)         system.out.println(datecompare(new date(), cal.gettime()));         // add 2 days         cal.add(calendar.date, 2);         // compare result (-1)         system.out.println(datecompare(new date(), cal.gettime()));                 }      public static int datecompare(date today, date date2) {         system.out.println("compare " + today + " " + date2);         return today.compareto(date2);     } } 

you make use of date api , use before , after...

date = new date();  calendar cal = calendar.getinstance(); cal.add(calendar.date, -1); system.out.println(now + " isbefore " + cal.gettime() + " = " + now.before(cal.gettime())); system.out.println(now + " isafter " + cal.gettime() + " = " + now.after(cal.gettime())); cal.add(calendar.date, 2); system.out.println(now + " isbefore " + cal.gettime() + " = " + now.before(cal.gettime())); system.out.println(now + " isafter " + cal.gettime() + " = " + now.after(cal.gettime())); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -