以HH:MM(非时间)的形式存储数值

时间:2013-11-02 13:38:12

标签: java variables date types

我需要弄清楚如何存储12:45, 13:45等时间..所以格式为HH:MM 在java中使用日期功能是不必要的,这些不会用于计算事件或任何事情的时间,我需要的只是执行13:45 - 12:45之类的操作并得到输出,在这种情况下是{ {1}}我尝试用双打执行此操作,但遇到01:00之类的问题,因为一小时内只有60分钟,预期输出应为13.45 + 00.35 = 13.80;

我正在试图弄清楚如何使用日期来做这件事,但请记住,此刻我不需要担心时区,日历日期等事情。我需要弄清楚如何制作数字表现得像小时和分钟。

很抱歉,如果这令人困惑。

5 个答案:

答案 0 :(得分:1)

您应该创建一个对象。称之为HHMM。它看起来像这样

public class HHMM {

  private int HH;
  private int MM;

  public HHMM(HH, MM) {

    this.HH = HH
    this.MM = MM

  }

  public toStr() {
    return HH + ":" + MM
  }

  public minus(HHMM hhmm){
    //write code here that subtracts the passed HHMM from this HHMM
  }

  //make a plus method too, and any other methods, etc.


}

答案 1 :(得分:1)

好的,这是我写的评论:

Calendar end = new GregorianCalendar(2013, 05, 05, 12, 40, 0);
Calendar start = new GregorianCalendar(2013, 05, 05, 12, 15, 0);

Calendar diff = end - start;
int minutes = diff.get(Calendar.Minutes);
int seconds = diff.get(Calendar.Seconds);

您不必使用日期部分来使用时间部分。

答案 2 :(得分:1)

Joda-Time已经在LocalTime课程中实现了您的目标:

LocalTime start = LocalTime.parse("12:45");
LocalTime end = LocalTime.parse("13:45");
Period period = new Period(start, end);

LocalTime start = new LocalTime(13, 45);
LocalTime later = start.plusMinutes(35);

答案 3 :(得分:0)

然后以分钟为单位存储所有数字。使用单个整数,您可以通过执行整数数学来进行简单的时间操作。如果您不关心它是哪一天,请将您的所有操作修改为1440(60 * 24):

示例:

int time = 600;

//Example time operation
time = (5000 + time) % 1440; //Day-insensitve

//Perform this check if you suspect time will become negative.
if(time < 0){
    time = 1440 + time;
}

//Display time
int hours = time / 60; //Integer division of 60, get the maximum number of "perfect 60s" in your time component.
int minutes = time % 60; //Integer mod, get the remainder since the last "perfect 60"

System.out.println(String.format("%02d:%02d", hours, minutes));

请注意,保留构造的大部分时间只是将时间/日期或任何内容存储为基本单位的单个数值。例如:System.currentTimeMillis(),它将时间作为自纪元以来的毫秒数。

如果只需要时间等简单的操作操作,则只需要了解如何将单个值解析为所需的组件(例如,秒,分钟,小时)。对这个数值的操作与传统数学一样。

答案 4 :(得分:0)

我使用一种方式在java中进行日期和小时的交易,我使用一个名为Joda-Time的框架,他非常好。只有你下载了。 Jar,并研究如何使用més,years和days进行操作的方法。使用这个框架vc可以通过执行更复杂的代码来节省很多麻烦。

相关问题