Java中可以使用java.util.Date
类和java.text.SimpleDateFormat
类来实现时间时钟。
首先,创建一个TimerTask
的子类,用于定时更新时间。在该子类中,可以使用java.util.Date
类获取当前时间,并将其转换为指定格式的字符串。然后,可以使用System.out.println()
方法将时间输出到控制台。
import java.util.Date;import java.util.TimerTask;import java.text.SimpleDateFormat;public class TimeClock extends TimerTask {@Overridepublic void run() {Date currentTime = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String formattedTime = sdf.format(currentTime);System.out.println(formattedTime);}}
接下来,在main()
方法中创建一个java.util.Timer
对象,并使用schedule()
方法安排定时任务。在每隔一秒中执行一次定时任务。
import java.util.Timer;public class Main {public static void main(String[] args) {Timer timer = new Timer();TimeClock timeClock = new TimeClock();timer.schedule(timeClock, 0, 1000);}}
运行上述代码,即可实现一个简单的时间时钟。每秒钟输出一次当前时间。