2016-10-01 69 views
1

我正试图收集小时的分钟。这似乎在这个班上工作。现在我想在其他类中使用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) { 
    } 
} 

回答

1

您需要将intTime定义为类成员。在你的代码中,intTime只在构造函数中是“活的”。

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 
    } 
} 
0

TL;博士

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类取代的麻烦的旧式遗留日期 - 时间类。 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.time框架是建立在Java 8和更高版本。这些类代替了令人讨厌的旧日期时间类,例如java.util.Date,.Calendar,& java.text.SimpleDateFormat

Joda-Time项目现在位于maintenance mode,建议迁移到java.time。请参阅Oracle Tutorial。并搜索堆栈溢出了很多例子和解释。

大部分的java.time功能后移植到Java 6 和ThreeTenABP还适于Android(见How to use…)。

ThreeTen-Extra项目扩展java.time与其他类。这个项目是未来可能增加java.time的一个试验场。您可以在这里找到一些有用的类,如Interval,YearWeek,YearQuartermore

相关问题