How i convert String to int? [duplicate]

2019-09-22 13:39发布

问题:

This question already has an answer here:

  • Java: getMinutes and getHours 12 answers
  • How can I prevent java.lang.NumberFormatException: For input string: “N/A”? [closed] 5 answers

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

回答1:

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;



回答2:

That is not the correct way to get minutes. If you are using Java 8 or higher version you could do this to get minutes

LocalDateTime localDateTime=LocalDateTime.now();
System.out.println(localDateTime.getMinute()); 


回答3:

    LocalTime now = LocalTime.now(ZoneId.of("Indian/Mahe"));
    int currentMinuteOfHour = now.getMinute();
    System.out.println(currentMinuteOfHour);

On my computer this just printed

53

There’s no need to format the minutes into a string and parse it back.

Also the Date class is long outdated (no pun intended). Better to use java.time, the modern Java date and time API. It is so much nicer to work with. And as you can see, it provides for much simpler code.

The current minute depends on time zone. Therefore please provide your intended time zone where I put Indian/Mahe. You may use the current JVM time zone setting: ZoneId.systemDefault(). The setting may be changed at any time by other parts of your program or other programs running in the same JVM.

What went wrong in your code? Your String.format() call produced a string like Current Minutes : 43. This doesn’t conform with the syntax of an integer (43 alone would). Therefore you got the exception from trying to parse it with Integer.valueOf(str).

Tutorial link: Oracle tutorial: Date Time explaining how to use java.time.