Home >Java >javaTutorial >Android gets current system date and time
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss //获取当前时间 Date date = new Date(System.currentTimeMillis()); time1.setText("Date获取当前日期时间"+simpleDateFormat.format(date));
The second method
Calendar calendar = Calendar.getInstance(); //获取系统的日期 //年 int year = calendar.get(Calendar.YEAR); //月 int month = calendar.get(Calendar.MONTH)+1; //日 int day = calendar.get(Calendar.DAY_OF_MONTH); //获取系统时间 //小时 int hour = calendar.get(Calendar.HOUR_OF_DAY); //分钟 int minute = calendar.get(Calendar.MINUTE); //秒 int second = calendar.get(Calendar.SECOND); time2.setText("Calendar获取当前日期"+year+"年"+month+"月"+day+"日"+hour+":"+minute+":"+second);
The third method
Time t=new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。 t.setToNow(); // 取得系统时间。 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获取当前日期"+year+"年"+month+"月"+day+"日"+hour+":"+minute+":"+second);
If you are careful, you may find that 1 is added to the month. This is because it starts with 0 It is calculated, so add 1 when used. Those who come into contact with Android for the first time may not be able to understand it. time1, time2 and time3 are objects of TextView. Remember to initialize them before use.
TextView time1 = (TextView) findViewById(R.id.tv_time1); TextView time2 = (TextView) findViewById(R.id.tv_time2); TextView time3 = (TextView) findViewById(R.id.tv_time3);
I am preparing to publish and I am still thinking about posting the xml to you. If it comes out, please post it
<TextView android:id="@+id/tv_time1" android:layout_width="match_parent" android:layout_height="60dp" android:gravity="center" android:text="时间"/>
Finally, I ran it on the simulator and all three methods are available. It depends on your personal habits!
[Recommended Course: Android Video Tutorial]
The above is the detailed content of Android gets current system date and time. For more information, please follow other related articles on the PHP Chinese website!