2014-11-21 55 views
0

即时得到3914-01-06作为输出时,日期选择器选择的值输入 是2014年1月6日获得值

 int day = view.getDayOfMonth(); 
     int month= view.getMonth(); 
     int year = view.getYear(); 

     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
     String formatedDate = sdf.format(new Date(year, month, day)); 
     Log.d("test", "" + formatedDate);//Here i'am retrieving 3914 instead 2014 

回答

2

根据the documentationDate()的第一个参数是“年份减去1900年“。这就是为什么你得到3914(= 2014 + 1900)。正如文件还指出,使用CalendarGregorianCalendar而不是Date

+0

你能提供给我一些样本吗? – 2014-11-21 17:24:29

+0

如果你想继续使用'Date',只需从''year'变量中减去1900:'int year = view.getYear() - 1900;' – 2014-12-03 15:16:23

0

你更好地与日历的工作,这里有一个简单的例子:

public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Use the current date as the default date in the picker 
    final Calendar c = Calendar.getInstance(); 
    int year = c.get(Calendar.YEAR); 
    int month = c.get(Calendar.MONTH); 
    int day = c.get(Calendar.DAY_OF_MONTH); 

    // Create a new instance of DatePickerDialog and return it 
    return new DatePickerDialog(getActivity(), this, year, month, day); 
} 

public void onDateSet(DatePicker view, int year, int month, int day) { 
    // Do something with the date chosen by the user 
    int [] tabd=new int[3]; 
tabd[0]=day; 
    tabd[1]=month+1; 
    tabd[2]=year; 
    Button b1=(Button)getActivity().findViewById(R.id.yourButton); 
    String d=tabd[0]+"-"+tabd[1]+"-"+tabd[2]; 
// d is your string that contain the date now you can do whatever you want with it 

}

+0

如何在不同的类中获取该字符串以用于某些事情其他。当我尝试setText()时,它所做的就是将文本设置为所选日期。它不允许我将这些数据存储到字符串中以供其他地方使用。 – 2015-11-08 18:31:47