如何在Android应用程序中获取当前时间和日期?


当前回答

Use:

Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour + ":" + time.minute);

例如,这将为您提供“12:32”。

记得导入android.text.format.Time;。

其他回答

对于那些可能更喜欢定制格式的人,您可以使用:

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

然而,你可以有DateFormat模式,如:

"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

你可以简单地使用下面的代码:

 DateFormat df = new SimpleDateFormat("HH:mm"); // Format time
 String time = df.format(Calendar.getInstance().getTime());

 DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd"); // Format date
 String date = df1.format(Calendar.getInstance().getTime());

您可以从日历中单独获取时间和日期。

// You can pass time zone and Local to getInstance() as parameter

Calendar calendar = Calendar.getInstance();

int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int date = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);

你可以用:

import java.util.Calendar;
import java.util.Date;

Date currentTime = Calendar.getInstance().getTime();

Calendar中有许多常量可以满足您的所有需要。

检查Calendar类文档。

一件容易的事。您可以剖析时间,以获得当前时间的单独值,如下所示:

Calendar cal = Calendar.getInstance();

int millisecond = cal.get(Calendar.MILLISECOND);
int second = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);

// 12-hour format
int hour = cal.get(Calendar.HOUR);

// 24-hour format
int hourofday = cal.get(Calendar.HOUR_OF_DAY);

日期也一样,如下所示:

Calendar cal = Calendar.getInstance();

int dayofyear = cal.get(Calendar.DAY_OF_YEAR);
int year = cal.get(Calendar.YEAR);
int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
int dayofmonth = cal.get(Calendar.DAY_OF_MONTH);