Java language programming (three) display the current time of the computer system

  Our article mainly describes two ways to display the time. The first is to display the current GMT (Greenwich Mean Time), and the second is to display the time of your computer in the current time zone.

1. Display the current GMT (Greenwich Mean Time)

       The method currentTimeMillis in the System class returns the number of milliseconds from 00:00 on January 1, 1970 GMT to the current moment. Because 1970 is the time when the UNIX operating system was officially released, this time is also called the UNIX timestamp .

      You can use this method to get the current time, and then follow the steps below to calculate the current number of seconds, minutes, and hours:

      (1) Call System.currentTimeMillis() method to obtain the number of milliseconds from midnight on January 1, 1970 to the present in the variable totalMilliseconds

      (2) The total number of milliseconds totalMillisceonds divided by 1000 to get the total number of seconds totalSeconds

      (3) Get the current number of seconds through totalSeconds%60

      (4) Get the total number of minutes totalMinutes by dividing totalSeconds by 60

      (5) Get the current minutes through totalMinutes%60

      (6) Get the total hours totalHours by dividing the total minutes totalMinutes by 60

      (7) Get the current hours through totalHours%24

      Next is the program list:

public class Time {

    public static void main(String[] args) {
        long totalMilliseconds = System.currentTimeMillis();
        long totalSeconds = totalMilliseconds/1000;
        long currentSecond = totalSeconds%60;
        long totalMinutes = totalSeconds/60;
        long currentMinute = totalMinutes%60;
        long totalHours = totalMinutes/60;
        long currentHour = totalHours%24;
        System.out.println("Current time is"+currentHour+":"+currentMinute+":"+currentSecond+"GMT");

image

      Every time you re-execute this java program, the result will slowly increase.


2. Display the current time of the computer

      Get the current system time and date and format the output:

      java.text.SimpleDateFormat simpleDateFormat = new   java.text.SimpleDateFormat("yyyy-MM-dd");    

       java.util.Date currentTime = new java.util.Date();    
      String time = simpleDateFormat.format(currentTime).toString();

      At this time, currentTime is the current computer time. Then you can call the time directly, the specific running screenshot is as follows:

image

      The running results are in the output box below.

      Our next article will introduce numeric type conversion, character data types and operations, and String type. I hope we can learn together and make progress together, thank you.


Guess you like

Origin blog.51cto.com/15064656/2602785
Recommended