2012-08-25 46 views
0

過去幾天我一直在尋找從android 4.0的日曆視圖中獲取「可讀」日期的方法。我找不到適合我的問題的解決方案或例子。我確實以毫秒爲單位,但不是以日期格式。Android CalendarView:如何以正確格式獲取日期?

我的問題是:我有一個calendarview,我想用戶選擇的日期,顯示在logcat中的dateformat yy-mm-dd。

我習慣於從android 2.2的datepicker,我不熟悉calendarview,也找不到很多關於它的。有沒有人知道這個解決方案?

回答

5

好吧,這裏是如何做到這一點。當您在活動內部啓動日曆視圖活動或日曆視圖時,會將日期設置爲當前日期(即今天)。爲了得到這個當前的日期只使用了Java API提供的Calendar對象來獲取低於此日期例如:

Calendar date = Calendar.getInstance(); 
// for your date format use 
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd"); 
// set a string to format your current date 
String curDate = sdf.format(date.getTime()); 
// print the date in your log cat 
Log.d("CUR_DATE", curDate); 

得到更改日期,你必須這樣做

CalendarView myCalendar = (CalendarView) findViewById(R.id.myCalenderid); 

myCalendar.setOnDateChangeListener(myCalendarListener); 

OnDateChangeListener myCalendarListener = new OnDateChangeListener(){ 

public void onSelectedDayChange(CalendarView view, int year, int month, int day){ 

    // add one because month starts at 0 
    month = month + 1; 
    // output to log cat **not sure how to format year to two places here** 
    String newDate = year+"-"+month+"-"+day; 
    Log.d("NEW_DATE", newDate); 
} 
} 
+0

我一直在尋找爲解決方案將毫秒日期轉換爲正常的可讀格式,這就做到了! – LargeGlasses

+0

此代碼中的myCalendarListener是什麼? –

+0

@KalaJ它是一個OnDateChangeListener。請參閱api參考:http://developer.android.com/reference/android/widget/CalendarView.OnDateChangeListener.html –

0
long date = calenderView.getDate(); 
Calendar calendar = Calendar.getInstance(); 
calendar.setTimeInMillis(date); 
int Year = calendar.get(Calendar.YEAR); 
int Month = calendar.get(Calendar.MONTH); 
int Day = calendar.get(Calendar.DAY_OF_MONTH); 
//customize According to Your requirement 
String finalDate=Year+"/"+Month+"/"+Day;