davidp
davidp

Reputation: 30

Groovy: Converting a string to integer gives NumberFormatException

I am trying to get a date from this text:

{InstantSeconds=1581504140},ISO,Europe/Paris resolved to 2020-02-12T11:42:20

I tried doing

def text = "{InstantSeconds=1581504140},ISO,Europe/Paris resolved to 2020-02-12T11:42:20"
text = text.replaceAll("[^\\d.]", "")
text = text.substring(10)
println "${text}"

int result= Integer.parseInt("${text}");
println result

But I'm getting

java.lang.NumberFormatException: For input string: "20200212114220"

I'm using this (for practice) https://groovyconsole.appspot.com/

Does anyone know why that happens?

Upvotes: 1

Views: 607

Answers (1)

ou_ryperd
ou_ryperd

Reputation: 2131

The value is too long for an integer. Use a Long datatype:

Long result = text.toLong()
assert result.class.name == 'java.lang.Long'
assert result == 20200212114220

Upvotes: 1

Related Questions