Three ways for Android to get the current system date and time

The first method

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");// HH:mm:ss
//Get current time
Date date = new Date(System.currentTimeMillis());
time1.setText("Date Get current date time"+simpleDateFormat.format(date));
  • 1
  • 2
  • 3
  • 4

The second method

Calendar calendar = Calendar.getInstance();
//Get the date of the system
//year
int year = calendar.get(Calendar.YEAR);
//month
int month = calendar.get(Calendar.MONTH)+1;
//day
int day = calendar.get(Calendar.DAY_OF_MONTH);
//get SysTime
//hour
int hour = calendar.get(Calendar.HOUR_OF_DAY);
//Minute
int minute = calendar.get(Calendar.MINUTE);
//second
int second = calendar.get(Calendar.SECOND);

time2.setText("Calendar Get current date"+year+"year"+month+"month"+day+"day"+hour+":"+minute+":"+second);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

The third method

Time t=new Time(); // or Time t=new Time("GMT+8"); plus Time Zone data.
t.setToNow(); // Get system time.
int year = t.year;
int month = t.month+1;
int day = t.monthDay;
int hour = t.hour; // 0-23
int minute = t.minute;
int second = t.second;
time3.setText("Calendar Get current date"+year+"year"+month+"month"+day+"day"+hour+":"+minute+":"+second);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

**Carefully, it may be found that 1 should be added to the month. This is because it is calculated from 0, so 1 should be added to the time. The first time you touch Android, you may not understand the last one. Time1, time2 and time3 are TextView objects that need to be initialized when you remember to use them
**

TextView time1 = (TextView) findViewById(R.id.tv_time1);
TextView time2 = (TextView) findViewById(R.id.tv_time2);
TextView time3 = (TextView) findViewById(R.id.tv_time3);
  • 1
  • 2
  • 3

I'm going to publish. I'm still thinking about xml. I'll post it to you. No, just one

<TextView

        android:id="@+id/tv_time1"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:gravity="center"
        android:text="time"/>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

Finally, I run to the simulator in three ways, see personal habits!  

Tags: Android xml simulator

Posted on Thu, 13 Feb 2020 15:58:36 -0500 by Jagarm