我如何将String转换为int?

时间:2018-04-08 11:39:08

标签: java string int numberformatexception minute

这是Code,我试图将Minutes(String类型)转换为整数类型,但我有NumberFormatException错误,任何人都可以帮助我,我如何处理这种情况。谢谢。

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

3 个答案:

答案 0 :(得分:2)

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

在我刚才打印的电脑上

  

53

无需将分钟格式化为字符串并将其解析回来。

Date类也很久了(没有双关语)。最好使用现代Java日期和时间API java.time。与它合作真是太好了。正如您所看到的,它提供了更简单的代码。

当前分钟取决于时区。因此,请提供您放置Indian / Mahe的预定时区。您可以使用当前的JVM时区设置:ZoneId.systemDefault()。您可以随时通过程序的其他部分或在同一JVM中运行的其他程序更改该设置。

您的代码出了什么问题?您的String.format()来电产生了一个类似Current Minutes : 43的字符串。这不符合整数的语法(仅43会)。因此,您尝试使用Integer.valueOf(str)解析它时会遇到异常。

教程链接: Oracle tutorial: Date Time解释如何使用java.time

答案 1 :(得分:2)

这不是获得分钟的正确方法。如果您使用的是Java 8或更高版本,则可以执行此操作以获取分钟

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

答案 2 :(得分:1)

使用

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

您得到异常,因为您尝试将字符串“当前日期/时间:xx”转换为数字;

相关问题