Reputation: 24144
This is my below code which converts string to long datatype.
/**
* Parses a String into primitive long
* @param str
* @return
*/
public static long parseLong(String str){
try {
long result = Long.parseLong(str);
return result;
} catch(NumberFormatException ex){
//do nothing or log it
return 0L;
}
}
But for this String 2006-09-11 22:01:13
whenever it is passed to the above parseLong
method, I always get this exception-
java.lang.NumberFormatException: For input string: "2006-09-11 22:01:13"
I need to convert String to Long
. And in this method any type of String can be passed. So while I was debugging the code, I found out that it is throwing exception for this string- "2006-09-11 22:01:13"
. As far as my understanding goes, it shouldn't be throwing exception right? as we can convert any string to long by using Long.parseLong
method right?
Can anyone explain why I am getting this exception? As I am confuse now.. :-/
Upvotes: 1
Views: 971
Reputation: 21181
Strings with special characters can not directly parsed to long or int
. If you want to parse it to long or any type replace the special character first with ("").
or otherwise if you want to parse the above string as date then use simpleDate format as like this
SimpleDateFormat parser= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
java.util.Date d = null;
try {
d = parser.parse(str);
System.out.println("Parsed date is "+d);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
Then the output will be
Parsed date is Mon Sep 11 22:01:13 IST 2006
Upvotes: 1
Reputation: 51030
It has to be an exact integral number held in a string. e.g. "12345676" nothing else than a digit. "2006-09-11 22:01:13" contains whole lot of stuffs than a digit like "-" (hyphen), ":" (colon), " " (space), which are not digits.
Upvotes: 0
Reputation: 10995
Because your date String
isn't a Long
or a number to begin with. You want to use SimpleDateFormat to parse your date string to a valid Date object.
Upvotes: 1