设置SimpleDateFormat时的NumberFormatException
DateRangePicker的日期显示为:“yyyy-M-d”。 但我希望它显示日期为:“yyyy-MM-dd”。设置SimpleDateFormat时的NumberFormatException
我已经尝试了下面的代码:
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth, int yearEnd, int monthOfYearEnd, int dayOfMonthEnd) {
String selection1 = year + "-" + (monthOfYear+1) + "-" + dayOfMonth;
String selection2 = yearEnd + "-" + (monthOfYearEnd+1) + "-" + dayOfMonthEnd;
Long firstDateSelection = Long.parseLong(selection1);
Long secondDateSelection = Long.parseLong(selection2);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = new Date(firstDateSelection);
Date endDate = new Date(secondDateSelection);
formatter.format(startDate); formatter.format(endDate);
,但我得到NumberFromatException当我运行它,在 “龙firstDateSelection =的Long.parseLong(选择1)”?
帮助非常感谢:) 谢谢!
你得到NumberFormatException
,因为“1234年12月23日”不是一个有效的Long
号码,且您尝试将其转换为Long
这里:
Long firstDateSelection = Long.parseLong(selection1);
既然你已经为数字日,月,年,你可以简单地格式化(无需SimpleDateFormat
):
String dateString = String.format("%1$04d-%2$02d-%3$02d", year, monthOfYear, dayOfMonth);
简单它是最好的但有效的,谢谢你的回答:) –
如果选中的Javadoc约parseLong(串)
抛出 NumberFormatException 如果字符串不包含可分析的long。
正如你所看到的带“ - ”的字符串不是一个很长的数字,它会抛出异常。
如果你想正确地做到这一点,你必须创建一个日历,添加你通过参数(year,monthOfYear ...)传递给set(...)的值,然后使getTime()得到日期对象。
不要直接创建Date对象(new Date ...),因为其方法setHour等已被弃用。
一旦你有了,你就可以做.format(dateObject)。
selection1和selection2在字符串中包含字符 - 所以它是无效的Long因此NumberFormatException –
当您执行Long.parseLong(“2010-10-10”)''时,您会发生什么?你期望得到什么产出? – azizbekian
@azizbekian那么当这样的日期被选中时,输出确实是“2017-10-10”。这只是10月前的一个月和10月前的一个月,我希望前面的数字为零。所以不是2017-9-1,产量是2017-09-01。 –