我正在努力收集一小时的时间。这似乎适用于本课程。现在我想在其他类中使用intTime进行一些计算。我如何返回intTime。 我在返回实例的属性时尝试使用相同的原则,但时间与我使用的任何对象无关。 getIntTime可行吗?
import java.text.SimpleDateFormat;
import java.util.*;
public class Time extends Database{
public Time(){
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat ("HH:mm:ss");
String stringTime = sdf.format (cal.getTime());
int intTime = 0;
stringTime = stringTime.substring(3,5); // retrieve the minutes (is recorded as string)
intTime = Integer.parseInt(stringTime);
}
public String getStringTime() {
return intTime;
}
public static void main (String[] args) {
}
}
答案 0 :(得分:1)
您需要将intTime定义为类成员。在你的代码中,intTime是' living'只在构造函数内部。
import java.text.SimpleDateFormat;
import java.util.*;
public class Time extends Database{
// class member defined in the class but not inside a method.
private int intTime = 0;
public Time(){
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat ("HH:mm:ss");
String stringTime = sdf.format (cal.getTime());
// vars defined here, will be gone when method execution is done.
stringTime = stringTime.substring(3,5); // retrieve the minutes (is recorded as string)
// setting the intTime of the instance. it will be available even when method execution is done.
intTime = Integer.parseInt(stringTime);
}
public String getStringTime() {
return intTime;
}
public static void main (String[] args) {
// code here
}
}
答案 1 :(得分:0)
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )
.get( ChronoUnit.MINUTE_OF_HOUR )
Chenchuk的回答是正确的,应该被接受。
此处涉及的其他一些问题。
您可以将小时数作为int
原语或Integer
对象返回,而不是在问题中看到的字符串。
顺便说一句,避免像“时间”这样含糊不清的名字。如果你的意思是分钟,请说明。
public int getMinuteOfHour() {
int m = Integer.parseInt( yourStringGoesHere ) ;
return m ;
}
所有这些都是不必要的。您正在使用现在由java.time类取代的麻烦的旧遗留日期时间类。 java.time类已经提供了您的功能。
您的代码忽略了时区的关键问题。如果省略,则隐式应用JVM的当前默认时区。更好的具体。
我们将时区定义为ZoneId
。用它来获得ZonedDateTime
作为当前时刻。询问一小时的时间。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( z );
int minuteOfHour = zdt.get( ChronoUnit.MINUTE_OF_HOUR );
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧日期时间类,例如java.util.Date
,.Calendar
和& java.text.SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。
大部分java.time功能都被反向移植到Java 6& ThreeTen-Backport中的7,并进一步适应Android中的ThreeTenABP(见How to use…)。
ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如Interval
,YearWeek
,YearQuarter
和more。