Android/Java - Date Difference in days

前端 未结 18 899
感动是毒
感动是毒 2020-11-22 14:17

I am getting the current date (in format 12/31/1999 i.e. mm/dd/yyyy) as using the below code:

Textview txtViewData;
txtViewDate.setText(\"Today is \" +
              


        
18条回答
  •  盖世英雄少女心
    2020-11-22 14:40

    Not really a reliable method, better of using JodaTime

      Calendar thatDay = Calendar.getInstance();
      thatDay.set(Calendar.DAY_OF_MONTH,25);
      thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
      thatDay.set(Calendar.YEAR, 1985);
    
      Calendar today = Calendar.getInstance();
    
      long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
    

    Here's an approximation...

    long days = diff / (24 * 60 * 60 * 1000);
    

    To Parse the date from a string, you could use

      String strThatDay = "1985/08/25";
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
      Date d = null;
      try {
       d = formatter.parse(strThatDay);//catch exception
      } catch (ParseException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      } 
    
    
      Calendar thatDay = Calendar.getInstance();
      thatDay.setTime(d); //rest is the same....
    

    Although, since you're sure of the date format... You Could also do Integer.parseInt() on it's Substrings to obtain their numeric values.

提交回复
热议问题