2012-07-10 3 views
6

안녕하세요 저는 Android에서 신규입니다. 안드로이드에서 두 날짜 사이의 모든 날짜를 얻는 방법.genarate 날짜가 android의 두 날짜 사이에 있습니다.

예를 들면. 두 개의 문자열이 있습니다.
String first="2012-07-15";
String second="2012-07-21";

I 변환이 문자열에서 날짜를 얻을.

DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("MMM dd");
String mydate = df2.format(df1 .parse(first));

내가 제 1 및 제 2 문자열에서 두 날짜를 얻을이 방법

.

이제는이 두 날짜 사이의 모든 날짜도 표시합니다. 아무도 나를 찾을 수 없어요.

+3

아래로 사용하기 위해 자바 Calendar 클래스 메소드에 의존 할 수의 중복 가능성 [I 한 하루 날짜를 증가 수있는 방법 Java에서?] (http://stackoverflow.com/questions/428918/how-can-i-increment-a-date-by-one-day-in-java) - 루프에서 증가분을 생성하여 날짜 계열 – assylias

답변

24

날짜 계산시 하드 코드 된 값을 사용하지 않는 것이 좋습니다. 우리는

코드를

private static List<Date> getDates(String dateString1, String dateString2) 
{ 
    ArrayList<Date> dates = new ArrayList<Date>(); 
    DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd"); 

    Date date1 = null; 
    Date date2 = null; 

    try { 
     date1 = df1 .parse(dateString1); 
     date2 = df1 .parse(dateString2); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 

    Calendar cal1 = Calendar.getInstance(); 
    cal1.setTime(date1); 


    Calendar cal2 = Calendar.getInstance(); 
    cal2.setTime(date2); 

    while(!cal1.after(cal2)) 
    { 
     dates.add(cal1.getTime()); 
     cal1.add(Calendar.DATE, 1); 
    } 
    return dates; 
} 

볼이 작업을하고

List<Date> dates = getDates("2012-02-01", "2012-03-01"); 
    for(Date date:dates) 
     System.out.println(date); 
+0

정말 고마워요. –

+0

행복하게 도와 드릴 수 있습니다. – sunil

1
public class DummyWorks extends Activity 
{ 
static final long ONE_DAY = 24 * 60 * 60 * 1000L; 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    getDatesBetween("03/23/2011","03/28/2011"); 
} 

public static void getDatesBetween(String startDate,String endDate) { 


    long from=Date.parse(startDate); 

    long to=Date.parse(endDate); 

    int x=0; 

    while(from <= to) { 
      x=x+1; 
      System.out.println ("Dates : "+new Date(from)); 
      from += ONE_DAY; 
    } 
    System.out.println ("No of Dates :"+ x); 


} 
} 
+0

날짜에 밀리 초를 추가하면 일광 절약 시간 및 기타 이상한 시간대 변경으로 인해 실패 할 위험이 높습니다. – assylias

+0

감사합니다 @assylias, 이제는 "긴 ONE_DAY"를 변경 한 후 it.its가 올바른 결과를 얻었습니다. –

+0

안녕하세요 @Ramkiran이 답장을 보내 주셔서 감사합니다. 하지만 나는 long from = Date.parse (startDate);에 오류가있어 java.util.Date.parse에서 java.illegalArgumentException이라고합니다. –

관련 문제