如何获取当前时间并将其设置为时钟?

时间:2016-03-29 04:05:09

标签: java datetime

我正在制作一款小游戏,我想设置一个实时运行的时钟。我也喜欢它在24小时内,仅仅是为了美学。所以,例如,如果是在这里下午3:45,我将如何打印程序" 15:45"在用户的显示屏上?

我将如何进行此操作,以及我将使用哪些内容来开始此过程?

非常感谢。

如果你想知道,这就是我原来的情况,但我不认为它会真正运行,除非引用该方法,这导致时间在一整天只有一次正确。

private static void clock (int time)
{
    int clock = time;

    boolean tick = true;
    while (tick)
    {
        clock ++;
        try {
             Thread.sleep(60000);                 //1000 milliseconds is one second.
        } catch(InterruptedException ex) {
             Thread.currentThread().interrupt();
        }

        if (clock > 2400)
        {
            clock = 0;
        }

    }
    System.out.println();
    System.out.println("The current time is " + clock + ".");
    System.out.println();
}

3 个答案:

答案 0 :(得分:1)

选择系统日期为:

public static String timeStamp = new SimpleDateFormat("dd_MMM_yyyy")
            .format(Calendar.getInstance().getTime());

答案 1 :(得分:0)

在类的构造函数中运行此代码您的时间在任何帧上显示动态或者如果将 jTextField2.setText(时间); 替换为系统,也可以设置为consloe。 out.println(); 方法

    {
        final DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
ActionListener timerListener = new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            Date date = new Date();
            String time = timeFormat.format(date);
            jTextField2.setText(time);
        }
    };
Timer timer = new Timer(1000, timerListener);
    timer.setInitialDelay(0);
    timer.start(); 
        String date=new SimpleDateFormat("dd:MM:yyyy").format(Calendar.getInstance().getTime());
        jTextField3.setText(""+date);
}

答案 2 :(得分:0)

一些事情......首先,您应该熟悉Java Date API以及DateFormatSimpleDateFormat类。虽然它并不完美,但它肯定可以帮到你 不确定int的来源,但日期通常基于自1970年1月1日午夜以来毫秒的数量。
其次,你至关重要,至少在核心方法中。在每一分钟之后,线程唤醒,就像现在一样,以毫秒为单位获取当前时间,将其格式化为" HH:mm"形式的字符串,并将其打印出来。在一天结束时(没有双关语),你试图做出与this person想要的相反的事情。他/她有24小时的时间,但想要12小时的时间。

long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
dateforrow = dateFormat.format(cal1.getTime());

或类似的东西。