如何在Netbeans中获得系统时间?

时间:2011-11-01 03:35:58

标签: java date time

我想在JLabel中显示系统时间(不是日期)。我可以用这个日期进行比较吗?

背景:我正在开发一个Netbeans Java项目 - Multiplex Ticket Booking System。 如果电影已经开始,用户不应该预订票证。

我不了解Core Java。 所以请把答案冗长而清晰,这样即使是新手也能理解。

4 个答案:

答案 0 :(得分:1)

Calendar cal = Calendar.getInstance(); 
cal.getTime(); 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
time.setText(sdf.format(cal.getTime()));

时间--->名称JLabel

答案 1 :(得分:0)

要显示当前时间,您可以使用

    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
    jLabel1.setText("The current time is "+sdf.format(d));

查找电影是否已开始:

我们可以将电影的开始时间存储在Date数据类型中,并制作一个将电影的开始时间作为输入的功能,并将其与当前日期进行比较,以查找是否可以预订电影的票证

boolean Has_movie_started(Date movie_start_date){
        //gets the current time 
        Date current_time = new Date();
        //calculates the difference in Milliseconds between start of movie and current time 

        long difference_milliseconds = movie_start_date.getTime()-current_time.getTime();

        //getTime() method returns how many milliseconds have passed since January 1, 1970, 00:00:00 GMT


        boolean movie_started;

      // if the difference is positive that means that movie has much more milliseconds and then current date.  

            if(difference_milliseconds>0){
                movie_started = false;
            }
            else{
                movie_started = true;
            }

        return movie_started;
    }

如果影片尚未开始,则此函数返回false,否则为电影已启动。 您可以使用它来确定是否可以预订该电影的票证。 :)

答案 2 :(得分:0)

import java.text.SimpleDateFormat;
import java.util.Date;
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
System.out.println(d)

输出:2019年4月2日星期二11:32:45 这100%的时间有效:)

答案 3 :(得分:0)

我想贡献现代的答案。其他答案中使用的CalendarDateSimpleDateFormat类的设计都很差,幸运的是过时了。

java.time

    ZoneId cinemaTimeZone = ZoneId.of("America/Argentina/Tucuman");
    DateTimeFormatter timeFormatter
            = DateTimeFormatter.ofLocalizedTime(FormatStyle.MEDIUM)
                    .withLocale(Locale.forLanguageTag("es"));

    LocalDateTime movieStartTime = LocalDateTime.of(2019, Month.APRIL, 2, 8, 30);

    ZonedDateTime systemTime = ZonedDateTime.now(cinemaTimeZone);
    String displayTime = systemTime.format(timeFormatter);
    timeLabel.setText(displayTime);

    if (systemTime.isAfter(movieStartTime.atZone(cinemaTimeZone))) {
        System.out.println("Movie has started, no more tickets will be sold.");
    }

这将在您的8:02:40中显示一个类似JLabel的字符串(我假设它被称为timeLabel,但是您当然可以更改它)。

我正在使用内置的本地化时间格式来格式化时间(没有日期)。通过提供格式样式FULLLONGMEDIUMSHORT,您可以控制所需格式的简洁程度。您可以通过提供语言环境来控制文化风格。

ZonedDateTime.now()为我们提供了当前时间,我们将其用于与电影的开始时间进行比较。当然,比较应该在电影院所在的时区进行(如果您不希望America / Argentina / Tucuman,则可以放置其他地方)。

自从我在那个时区(电影开始时间)8:30之前运行了 代码之后,它没有打印了电影已开始 em>消息。如果我们稍后运行它,它将。

链接: Oracle tutorial: Date Time解释了java.time的用法。

相关问题