How i convert String to int? [duplicate]

徘徊边缘 提交于 2019-12-13 23:24:24

问题


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.



来源:https://stackoverflow.com/questions/49717423/how-i-convert-string-to-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!