java - 根据日期找到时间并希望将其从字符串转换为 int

标签 java string time int

我想找到当前时间和分钟,然后将 String 转换为 int,以便我可以使用它们。

我写了这段代码,但 Netbeans 总是向我显示这个错误:

   Exception in thread "main" java.lang.NumberFormatException: For input string: "mm "
   at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
   t JavaApplication1.JavaApplication1.main(JavaApplication1.java:66)
   C:\Users\eleft\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:

Java 返回:1 构建失败(总时间:0 秒)

    //HOURS   --12 hour form
        Date date1 = new Date();
        String strDateFormat1 = "hh ";
        DateFormat dateFormat1 = new SimpleDateFormat(strDateFormat1);
        String formattedDate1= dateFormat1.format(date1);

        System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate1);

        //MINUTES
        Date date2 = new Date();
        String strDateFormat2 = "mm ";
        DateFormat dateFormat2 = new SimpleDateFormat(strDateFormat2);
        String formattedDate2= dateFormat2.format(date);

        System.out.println("Current time of the day using Date - 12 hour format: " + formattedDate2+ "MINUTES");  


        int current_minutes=Integer.parseInt(strDateFormat2);    

        int current_hours=Integer.parseInt(strDateFormat1);

最佳答案

java.time

以 12 小时格式获取当前小时和以 int 值获取当前分钟:

LocalTime currentTime = LocalTime.now(ZoneId.of("Asia/Qatar"));

int currentHours = currentTime.get(ChronoField.HOUR_OF_AMPM);
int currentMinutes = currentTime.getMinute();

System.out.println("Current time of the day using LocalTime - 12 hour format: "
        + currentHours + " HOURS " + currentMinutes + " MINUTES");

刚才运行时的输出是:

Current time of the day using LocalTime - 12 hour format: 11 HOURS 52 MINUTES

请替换 your desired time zone我把亚洲/卡塔尔放在哪里。

currentTime.get(ChronoField.HOUR_OF_AMPM) 为您提供从 0 到 11 的小时数。如果您想要 12 而不是 0,只需使用 ChronoField.CLOCK_HOUR_OF_AMPM 而不是ChronoField.HOUR_OF_AMPM

你的代码出了什么问题?

首先,您使用的是旧的日期时间类 DateSimpleDateFormat。它们设计不佳且早已过时,所以不要那样做。相反,我使用的是现代 Java 日期和时间 API java.time。您可能已经注意到这也极大地简化了您的代码(结合下一点)。

其次,您格式化小时和分钟只是为了解析它们。这就是弯路。不要那样做。

第三,正如其他答案正确指出的那样,您试图解析 strDateFormat2,该变量包含格式模式 mm 而不是包含数字的字符串。您收到的异常消息 For input string: "mm " 试图告诉您这一点。几个小时也是如此。

第四,正如 Tejas Jagtap 正确所说,Integer.parseInt 将拒绝解析带有尾随空格的字符串。

链接

Oracle tutorial: Date Time解释如何使用现代 Java 日期和时间 API java.time

关于java - 根据日期找到时间并希望将其从字符串转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54031335/

相关文章:

Java - 捕获html标签

Python 使用正则表达式拆分字符串

java - 一年中一周的即时时间

java - 检查 Firebase 中是否存在值?

java - JButton 和 JFileChooser 的错误消息

c++ - 在 C++ 中将 Double 转换为 String 时精度丢失

Python Selenium,逐个字母发送键

java - 使用java代码更改ubuntu系统时间

java - 为微调器实现 onItemSelectedListener

python - 计算文件中字符串的出现次数时,我的代码不计算第一个单词