Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Date difference  RSS feed

 
madhup narain
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
i have a date string dd.mm.yyyy

whats the best method to find the date difference between the string dd.mm.yyyy and the current date.


Regards
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use java.text.SimpleDateFormat.parse() to convert a string to a Date object. Once you have that you can compare it to "new Date()" any way you like (the current Date will of course have hours, minutes and so on set, so if you're just interested in the day you can't compare them directly using compareTo).
 
madhup narain
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
heres what i wrote!

Date currentDate = new Date();
Date userDate = null;

int hrs1= currentDate.getHours();
int min1= currentDate.getMinutes();
int sec1= currentDate.getSeconds();

//convert it to dd.mm.yyyy.hh.MM.ss
date = date +"."+ hrs1+"."+min1+"."+sec1;

SimpleDateFormat oSimpleDateFormat = new SimpleDateFormat("dd.MM.yyyy.HH.mm.ss");
try{
userDate=oSimpleDateFormat.parse(date);
}catch(Exception e){
// do something
}

System.out.println("userDate------>"+userDate);
System.out.println("currentDate--->"+currentDate);

long daterange = userDate.getTime() - currentDate.getTime();
long time = 1000*3600*24; //A day in milliseconds

System.out.println("Difference "+daterange/time);




The difference is not consistent.


userDate------>Thu Aug 18 17:12:48 IST 2005
currentDate--->Tue Aug 16 17:12:48 IST 2005
Difference 1

but shud be 2
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

long daterange = userDate.getTime() - currentDate.getTime();
long time = 1000*3600*24; //A day in milliseconds

System.out.println("Difference "+daterange/time);


'currentDate' has a milliseconds part, which ensures that 'daterange' will not be evenly divisable by 'time'.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!