Home > Java > javaTutorial > body text

Android gets current system date and time

little bottle
Release: 2019-04-09 14:24:25
forward
9072 people have browsed it


This article uses three methods to implement the time acquisition function on Android. If you like it, save it and give it a try!

The first method

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));
Copy after login

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);
Copy after login

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);
Copy after login

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);
Copy after login

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="时间"/>
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template