Search code examples
javastringintnumber-formattingnumberformatexception

Java Number Format Exception in Conversion from String to Integer


The following program Generate Unique key by using Date and Time(using joda time API)

import org.apache.commons.codec.binary.Base64;
import org.joda.time.*;

public class EnDecoding {


    public String EncodeRecieverAddress(String emailaddress){
        byte[] encodedBytes = Base64.encodeBase64(emailaddress.getBytes());
        return new String(encodedBytes);
    }

    public String DecodeRecieverAddress(String encodedemail){
        byte[] decodedBytes = Base64.decodeBase64(encodedemail.getBytes());
        return new String(decodedBytes);
    }

    public int GenerateUniquekey() {
        LocalTime localtime = new LocalTime();
        LocalDate localdate = new LocalDate();
        String  key = "" + localdate.getDayOfYear()   
                    + localdate.getDayOfMonth()
                    + localdate.getDayOfWeek()
                    + localtime.getHourOfDay()
                    + localtime.getMinuteOfHour()
                    + localtime.getSecondOfMinute()
                    + localtime.getMillisOfSecond();
        System.out.println(key);
        System.out.println(Integer.parseInt(key.trim()));
      return 0;
    }
}

System.out.println(key);

Output : 117275232750437

System.out.println(Integer.parseInt(key.trim()));

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

I have used id.trim() function to eliminates leading and trailing spaces , but that does not solve my problem too.

Please dont mark this question duplicate as because other similar kind of questions didnt help me much that's why i have created this new question and so I hope to get the best answer over here.


Solution

  • Maximum value of integer is 2,147,483,647, your input is too large. Use Long instead.