java 将时间添加到日历

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12776816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:10:43  来源:igfitidea点击:

Adding time to calendar

java

提问by Theway2cool1

Possible Duplicate:
How to subtract X days from a date using Java calendar?

可能的重复:
如何使用 Java 日历从日期中减去 X 天?

This should be fairly simple to answer, but I want to know: if you, for example, added 50 seconds to a Calendar, and the current seconds were 20, would it add 1 minute and set the seconds to 10, or set seconds to 70? Here's a bit of code to better demonstrate what I mean:

这应该很容易回答,但我想知道:例如,如果您向日历添加 50 秒,而当前秒数为 20,是否会添加 1 分钟并将秒数设置为 10,或将秒数设置为70?这里有一些代码可以更好地说明我的意思:

Calendar cal;  
public void test(){  
cal.add(Calendar.SECOND, 50);  
}

So, let's say that when that code ran, the current second was 20 and the current minute was 10. Would it go to 11 minutes, 10 seconds, or 10 minutes, 70 seconds? Thanks in advance.

因此,假设当该代码运行时,当前秒为 20,当前分钟为 10。它会变为 11 分 10 秒还是 10 分 70 秒?提前致谢。

回答by obe6

I neither try it, but I expect it will pass to 1 minute and 10 seconds.

我没有尝试过,但我希望它会传递到 1 分 10 秒。

...now i tried and obviously is confirmed :

...现在我试过了,显然已经确认:

public class Test {

public static void main(String[] args) {
    Calendar cal = GregorianCalendar.getInstance();
    System.out.println("Minutes : "+ cal.get(Calendar.MINUTE));
    System.out.println("Seconds :" + cal.get(Calendar.SECOND));
    cal.add(Calendar.SECOND, 50);
    System.out.println("Minutes : "+ cal.get(Calendar.MINUTE));
    System.out.println("Seconds :" + cal.get(Calendar.SECOND));
}

}

}

Printed to my console :

打印到我的控制台:

Minutes : 11
Seconds :33
Minutes : 12
Seconds :23

回答by Damian Leszczyński - Vash

The time that you are describing is only the format of it. In reallity the value of date is stored as longnumber. By invoking Calendar#add(type,value)method with proper parameters you just add/substrac value to that longnumuber.

您所描述的时间只是它的格式。实际上,日期的值存储为long数字。通过Calendar#add(type,value)使用适当的参数调用方法,您只需向该long数字添加/减去值。

The 0 value of that number represent the posix time, 1 January 1970

该数字的 0 值代表posix 时间,1970 年 1 月 1 日

And the value 1349591726, represent after formating 2012-10-07 06:35:26Z

和值1349591726,表示格式化后2012-10-07 06:35:26Z