Search code examples
javastringintnumberformatexceptionminute

How i convert String to int?


Here's Code, I am trying to convert Minutes which is String type, to integer type but I am having NumberFormatException error, can anyone help me, how i handle this situation. Thanks.

import java.util.Date;

class DateDemo 
{
    public static void main(String args[]) 
    {
        // Instantiate a Date object
        Date date = new Date();

        // display time and date
        String str = String.format("Current Minutes : %tM", date );
        try
        {
            int a = Integer.valueOf(str);
            System.out.print(a);

        }
        catch(NumberFormatException e)
        {
            System.out.println("Error is : "+e);
        }
    }
}

Solution

  • Use

    String str = String.format("%tM", date );
    

    You get the exception because you try to convert a String "Current Date/Time : xx" to a number;