dee*_*pak 5 android date android-date
我想从特定日期获得日期,月份和年份.
我使用下面的代码:
String dob = "01/08/1990";
int month = 0, dd = 0, yer = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date d = sdf.parse(dob);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
month = cal.get(Calendar.MONTH);
dd = cal.get(Calendar.DATE);
yer = cal.get(Calendar.YEAR);
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
所以从上面的代码我得到了 month -0 , yer - 1990 and date - 8
但我想要month - 01 , date - 08 and yer - 1990.
我也定义了日期格式,但我没有从日期,月份和年份获得完美的价值.
日历中的月份将是0-11.您必须在月内添加+1.
String dob = "01/08/1990";
String month = 0, dd = 0, yer = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date d = sdf.parse(dob);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
month = checkDigit(cal.get(Calendar.MONTH)+1);
dd = checkDigit(cal.get(Calendar.DATE));
yer = checkDigit(cal.get(Calendar.YEAR));
} catch (Exception e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
用于添加前零的checkDigit方法.checkDigit()方法返回String值.如果你想要整数转换,那么你可以这样做Integer.parseInt(YOUR_STRING);
// ADDS 0 e.g - 02 instead of 2
public String checkDigit (int number) {
return number <= 9 ? "0" + number : String.valueOf(number);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6074 次 |
| 最近记录: |