[英]Can't convert from String to int in Java
I'm getting the current time and I want to convert it into Integer, thats what I did , but it keeps giving me java.lang.NumberFormatException: For input string: "4:12:31"
我正在获取当前时间,并且想要将其转换为Integer,这就是我所做的,但是它一直给我java.lang.NumberFormatException: For input string: "4:12:31"
long unixTime = System.currentTimeMillis() / 1000L;
Date time=new java.util.Date((long)unixTime*1000);
Calendar cal = Calendar.getInstance();
cal.setTime(time);
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
int currentTime = (int) Double.parseDouble((hours+":"+minutes+":"+seconds));
You cannot do that. 你不能这样做。 If you need to compare times, use LocalTime. 如果需要比较时间,请使用LocalTime。
LocalTime b = LocalTime.of(17, 30);//hh,mm,ss
LocalTime c = LocalTime.parse("20:30:30");//hh:mm:ss
System.out.println(b.isBefore(c));//true, also there are methods like compareTo, isAfter
If you need to compare dates, there is also a class called LocalDate
. 如果需要比较日期,则还有一个名为LocalDate
的类。 If you need to compare both dates and time, you can use LocalDateTime
. 如果您需要比较日期和时间,则可以使用LocalDateTime
。 Comparing those objects is the same, as comparing two LocalTime
obejcts. 比较两个对象与比较两个LocalTime
对象是相同的。
LocalTime.of
and .parse
are static factory methods. LocalTime.of
和.parse
是静态的工厂方法。 They are used to create new instances of LocalTime
. 它们用于创建LocalTime
新实例。 From a user perspective, they work like constructors — you call them and you receive in return an object of its class. 从用户的角度来看,它们就像构造函数一样工作—调用它们,然后您将收到其类的对象作为回报。 More about them and constructors you can read here: Java Constructors vs Static Factory Methods . 有关它们和构造函数的更多信息,请参见此处: Java构造函数与静态工厂方法 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.