Get current time and date on Android

2018-12-31 04:00发布

How can I get the current time and date in an Android app?

30条回答
浪荡孟婆
2楼-- · 2018-12-31 04:36

For those who might rather prefer a customized format, you can use:

DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date = df.format(Calendar.getInstance().getTime());

Whereas you can have DateFormat patterns such as:

"yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
"hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
"EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
"yyMMddHHmmssZ"-------------------- 010704120856-0700
"K:mm a, z" ----------------------- 0:08 PM, PDT
"h:mm a" -------------------------- 12:08 PM
"EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
查看更多
情到深处是孤独
3楼-- · 2018-12-31 04:36
Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour+":"+time.minute);

This will give you, for example, 12:32.

Remember to import android.text.format.Time;

查看更多
其实,你不懂
4楼-- · 2018-12-31 04:37
final Calendar c = Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
    int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);

textView.setText(""+mDay+"-"+mMonth+"-"+mYear);
查看更多
不流泪的眼
5楼-- · 2018-12-31 04:38

try to use below code:

 Date date = new Date();
 SimpleDateFormat dateFormatWithZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault());  
 String currentDate = dateFormatWithZone.format(date);
查看更多
只靠听说
6楼-- · 2018-12-31 04:39
Time now = new Time();
now.setToNow();

Try this works for me as well.

查看更多
浮光初槿花落
7楼-- · 2018-12-31 04:40

This is a method that will be useful to get date and time:

private String getDate(){
    DateFormat dfDate = new SimpleDateFormat("yyyy/MM/dd");
    String date=dfDate.format(Calendar.getInstance().getTime());
    DateFormat dfTime = new SimpleDateFormat("HH:mm");
    String time = dfTime.format(Calendar.getInstance().getTime());
    return date + " " + time;
}

You can call this method and get the current date and time values:

2017/01//09 19:23
查看更多
登录 后发表回答