2013-07-28 58 views
1

當我從mySQL得到一個日期,其格式爲2013-06-05,但是當我嘗試在日期選擇器對話框中顯示它時,我得到的是1933年,而且這個月份和日期也不正確。如何格式化mySQL日期以顯示在android中的datepicker?

變量Setdate將是字符串"2013-06-05"

 public void onClick(View v) { 
      // TODO Auto-generated method stub 
      String Setdate = dateButton.getText().toString(); 
      SimpleDateFormat sfd = new SimpleDateFormat(Setdate); 
      Calendar myCalendar = sfd.getCalendar(); 
      new DatePickerDialog(context, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show(); 
     } 

有誰知道如何解決這個問題?

感謝

回答

2

SimpleDateFormat的構造函數在模式字符串,而不是實際日期字符串。模式字符串描述格式它應該在解析日期字符串或將日期轉換爲字符串表示形式時使用。

試試這個:

String format = "yyyy-MM-dd"; 
SimpleDateFormat sdf = new SimpleDateFormat(format); 
String dateString = dateButton.getText().toString(); 
Date date = sdf.parse(dateString); 
Calendar myCalendar = Calendar.getInstance(); 
myCalendar.setTime(date); 
new DatePickerDialog(context, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show(); 

另一種思考:如果你在的日期是如何存儲的控制,也許是考慮將他們作爲代表紀元以來,這是什麼日期和Calendar類內部使用毫秒多頭無論如何。它往往可以使代碼更容易,例如:

long time = ... 
Calendar myCalendar = Calendar.newInstance(); 
myCalendar.setTimeInMillis(time); 
new DatePickerDialog(context, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show(); 
0

你可以嘗試這樣的

DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); 
    Date date=df.parse("2013-06-05"); 
    String text = df.format(date); 
    System.out.println("The date is: " + text); 
1

東西將字符串轉換爲日期您可以使用的SimpleDateFormat的解析功能。

String myFormat = "yyyy-MM-dd"; 
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US); 
Date dateObj = sdf.parse(dateStr); 
Calendar myCal = Calendar.getInstance(); 
myCal.setTime(dateObj); 

要將日期存儲在DatePicker對象中,需要使用Calendar.get()函數提取月份,日期和年份。然後使用DatePicker.init()設置日期並創建一個OnDateChangedListener來知道用戶何時更改日期。

int month = myCal.get(Calendar.MONTH); 
int day = myCal.get(Calendar.DATE); 
int year = myCal.get(Calendar.YEAR); 
mDp.init(year, month, day, new OnDateChangedListener() { 
     public void onDateChanged(DatePicker view, int year, 
     int monthOfYear, int dayOfMonth) { 
      // To-Do (what ever I need to do when the date is changed). 
     } 
     }); 

將日期從DatePicker對象中取出。

Date myDate = new Date(mDp.getYear() - 1900, mDp.getMonth(), 
     mDp.getDayOfMonth()); 

將其轉換回ISO格式的日期或格式化爲正確的語言環境。

String myFormat = "yyyy-MM-dd"; 
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US); 
String dateAddedISO = sdf.format(myDate); 
String dateAdded = DateFormat.getDateInstance().format(myDate); 
相關問題