Number format exception while parsing the date to

2019-09-22 07:50发布

问题:

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));