【问题标题】:How to get the current time and set it to a clock? [duplicate]如何获取当前时间并将其设置为时钟? [复制]
【发布时间】:2016-03-29 04:05:08
【问题描述】:

我正在创建一个小游戏,我想设置一个非实时时钟。我也希望它在 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();
}

【问题讨论】:

  • java.time.LocalTime 时间 = LocalTime.now();会给你当前时间
  • SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); String str = sdf.format(new Date());
  • 这适用于任何设备,包括 Apple 和 Microsoft?
  • 无论在什么平台上运行,它都适用于任何 jvm(LocalTime 版本 8+)
  • 谢谢!我很感激。

标签: java datetime


【解决方案1】:

选择系统日期为:

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

【讨论】:

    【解决方案2】:

    有几件事......首先,您应该真正熟悉 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());
    

    或类似的东西。

    【讨论】:

    • 这很有意义。我会尽量记住这些信息,我非常感激。谢谢!
    【解决方案3】:

    在类的构造函数中运行此代码,您的时间在任何帧上都显示为动态或者如果您将 jTextField2.setText(time); 替换为 System,您也可以设置为 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2020-07-02
      • 2016-02-01
      • 2012-01-10
      相关资源
      最近更新 更多