Number format exception while parsing the date to long

依然范特西╮ 提交于 2019-12-13 10:45:34

问题


I'm getting a NumberFormatException while executing the below statements.

Calendar cal = Calendar.getInstance();

int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day_of_month = 15;

long m_time = Long.parseLong((month + 1) + "/" + day_of_month + "/" + year);

and

long m_time = Long.parseLong(String.valueOf((month + 1) + "/" + day_of_month + "/" + year));

回答1:


The reason for the NumberFormatException is cause you are trying to parseLong a String that is not a valid long representation: "2/15/2015"

To parse the date string you've come up with correctly use this code:

SimpleDateFormat format = new SimpleDateFormat("M/dd/yyyy");
Date date = format.parse(month + 1 + "/" + day_of_month + "/" + year);



回答2:


"2/15/2015" type of string cannot be parsed by the Long.parseLong() method. Use SimpleDateFormat.

String string_date = "15-January-2015";

SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date d = f.parse(string_date);
long milliseconds = d.getTime();



回答3:


You're attempting to parseLong on a concatenated string with a lot of non-numeric characters.

If you're trying to obtain the Long value of a given date:

Calendar myCalendar = Calendar.getInstance();
Date now = myCalendar.getTime();   // date object of today
System.out.println(now.getTime()); // prints long value of today

myCalendar.set(Calendar.DAY_OF_MONTH, 15);
Date then = myCalendar.getTime();  // date object for the 15th
System.out.println(then.getTime());// prints long value again but for the 15th

If you're looking to format a Date object to a String:

SimpleDateFormat format = new SimpleDateFormat("M/d/YYYY");
System.out.println(format.format(now));
System.out.println(format.format(then));


来源:https://stackoverflow.com/questions/28259818/number-format-exception-while-parsing-the-date-to-long

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!