Java当前时间需要递增的方法

标签 java date

我创建了一个方法来获取当前时间,我希望每次调用此方法时时间都会增加 60 秒或 1 分钟。任何帮助将不胜感激。

//我当前使用的方法

public String currentTime() 
{
    Calendar cal = Calendar.getInstance();
    cal.getTime();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    return sdf.format(cal.getTime());
}

//主要

System.out.println("The time is now: " + d.currentTime());

最佳答案

首先,您需要在第一次调用该方法时“捕捉”当前时间。一秒偏移量将添加到后续调用中。然后,只需记录该方法被调用的次数,并将其应用为以秒为单位的偏移量:

static int offset;
static long firstCall;

public static void main(String[] args)
{
    System.out.println(currentTime());
    System.out.println(currentTime());
    System.out.println(currentTime());
}

public static String currentTime()
{
    if (offset == 0)
    {
        firstCall = System.currentTimeMillis();
    }

    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(firstCall + (offset * 1000 * 60));
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    offset++;
    return sdf.format(cal.getTime());
}

为了说明这一点,我们必须将调用次数 (1, 2, 3) 转换为以毫秒为单位的偏移量。因此,我们乘以 1000 得到 1 秒,然后乘以 60 得到分钟。

第一次调用该方法时,偏移量为0。因此,第一次调用该方法时会添加0秒/毫秒。

关于Java当前时间需要递增的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20024161/

相关文章:

java - 从html文件获取文本字段字符串输入以在java类中处理/使用

java - 日期构造函数java

r - 将表示不同格式日期的字符串列转换为日期列

Excel:将美国日期格式转换为欧洲格式

java - 如何使用 Java Date 类将验证添加到进入另一年的日期

Maven 中的 Java EE 7 First Cup 教程错误 : Could not find artifact org. glassfish.javaeetutorial.firstcup :firstcup:pom:7. 0.1-SNAPSHOT

java - p6spy 找不到适合 com.mysql.jdbc.Driver 的驱动程序

java - 迁移到 Hibernate 4、@Inheritance 和 @GenerateValue 的误解

java - OpenGL混合: Remove pixels being drawn over (immediate mode)

Php/Mysql 日期保存为 '0000-00-00'