2015年11月16日 星期一

[ Java 代碼範本 ] Joda - Calculate the number of days between two dates

Question 
In Java, I want to calculate the number of days between two dates as Date type. 

How-To 
Well to start with, you should only deal with them as strings when you have to. Most of the time you should work with them in a data type which actually describes the data you're working with. I would recommend that you use Joda Time, which is a much better API than Date/Calendar. It sounds like you should use theDays type in this case. You can then use: 
  1. package test  
  2.   
  3. import java.text.SimpleDateFormat  
  4.   
  5. import org.joda.time.DateTime;  
  6. import org.joda.time.Days;  
  7.   
  8.   
  9. String date1Str = '2015/05/03'  
  10. String date2Str = '2015/06/10'  
  11.   
  12. SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd")  
  13.   
  14. Date d1 = sdf.parse(date1Str)  
  15. Date d2 = sdf.parse(date2Str)  
  16.   
  17. DateTime f = new DateTime(d1.getTime())  
  18. DateTime t = new DateTime(d2.getTime())  
  19.   
  20. printf("Between %s ~ %s = %d days!\n", date1Str, date2Str, Days.daysBetween(f, t).getDays()+1)  
Execution result: 
Between 2015/05/03 ~ 2015/06/10 = 39 days!

Supplement 
Joda Online API 
Calculating the difference between two Java date instances

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...