Real-time refresh time and time format conversion in java

1. To obtain time in Java, you generally use
Date d =new Date();
to return a Date time type Wed May 13 11:19:27 CST 2020

2. Convert the date and time format to
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd ");
SimpleDateFormat sdf3 = new SimpleDateFormat("HH :mm:ss”);
System.out.println(sdf.format(new Date()));
System.out.println(sdf2.format(new Date()));
System.out.println(sdf3.format (new Date()));
SimpleDateFormat class formats the output format of dates.

3. Convert system milliseconds to Date date format
long timeLong = System.currentTimeMillis();//Get system time
Date date = new Date();
date.setTime(timeLong);

4. Get the year, month, day, hour, minute and second based on the current system time
long timeLong = System.currentTimeMillis();//Get the system time
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timeLong);
int year = calendar.get(Calendar .YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int hour24 = calendar.get(Calendar.HOUR_OF_DAY);//24-hour format
int hour12 = calendar. get(Calendar.HOUR);//12-hour format
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);

5. Get the year, month, day, hour, minute and second based on the Date class
Date date = new Date();
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR); //Get the year
int month = calendar. get(Calendar.MONTH) + 1; //Get the month. The month starts from 0
int date = calendar.get(Calendar.DATE); //Get the day
// calendar.get(Calendar.HOUR); //Hour (12 hours system)
int hour = calendar.get(Calendar.HOUR_OF_DAY); //Hour (24-hour system)
int minute = calendar.get(Calendar.MINUTE); //Minute
int second = calendar.get(Calendar.SECOND); / /second calendar.setTime(date);

6. Real-time refresh system time bold style
1). Thread + infinite loop
Thread thread1 = new Thread() { @Override public void run() { while (true) { Date date = new Date(); //data each Refreshed once a second. Refresh coverage //own logic processing } try { sleep(1000); } catch (Exception e) { } } } }; thread1.start();














Guess you like

Origin blog.csdn.net/rainAndyou/article/details/106094192