gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:31:25 25 4
gpt4 key购买 nike

我创建了一个方法来获取当前时间,我希望每次调用此方法时时间都会增加 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com