在Android中如何获取当前时间和日期

1288

我该如何在Android应用中获取当前的时间和日期?


8
43个回答!虽然其中许多回答在撰写时是很好的,但2018年可以使用的好答案在这里 - Ole V.V.
@OleV.V. 2023年怎么样? - user16217248
2
@user16217248,我仍然推荐我之前链接的Basil Bourque的答案 - Ole V.V.
43个回答

34

简单。您可以将时间分解为当前时间的不同值,如下所示:

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);

如何获取接下来5-10天的日期?这里需要手动计算吗? - CoDe
@CoDe 你可以使用日期来实现。 - FindOutIslamNow

28
SimpleDateFormat databaseDateTimeFormate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
SimpleDateFormat databaseDateFormate = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("dd.MM.yy");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
SimpleDateFormat sdf3 = new SimpleDateFormat("EEE, MMM d, ''yy");
SimpleDateFormat sdf4 = new SimpleDateFormat("h:mm a");
SimpleDateFormat sdf5 = new SimpleDateFormat("h:mm");
SimpleDateFormat sdf6 = new SimpleDateFormat("H:mm:ss:SSS");
SimpleDateFormat sdf7 = new SimpleDateFormat("K:mm a,z");
SimpleDateFormat sdf8 = new SimpleDateFormat("yyyy.MMMMM.dd GGG hh:mm aaa");


String currentDateandTime = databaseDateTimeFormate.format(new Date());     //2009-06-30 08:29:36
String currentDateandTime = databaseDateFormate.format(new Date());     //2009-06-30
String currentDateandTime = sdf1.format(new Date());     //30.06.09
String currentDateandTime = sdf2.format(new Date());     //2009.06.30 AD at 08:29:36 PDT
String currentDateandTime = sdf3.format(new Date());     //Tue, Jun 30, '09
String currentDateandTime = sdf4.format(new Date());     //8:29 PM
String currentDateandTime = sdf5.format(new Date());     //8:29
String currentDateandTime = sdf6.format(new Date());     //8:28:36:249
String currentDateandTime = sdf7.format(new Date());     //8:29 AM,PDT
String currentDateandTime = sdf8.format(new Date());     //2009.June.30 AD 08:29 AM
日期格式模式
G   Era designator (before christ, after christ)
y   Year (e.g. 12 or 2012). Use either yy or yyyy.
M   Month in year. Number of M's determine length of format (e.g. MM, MMM or MMMMM)
d   Day in month. Number of d's determine length of format (e.g. d or dd)
h   Hour of day, 1-12 (AM / PM) (normally hh)
H   Hour of day, 0-23 (normally HH)
m   Minute in hour, 0-59 (normally mm)
s   Second in minute, 0-59 (normally ss)
S   Millisecond in second, 0-999 (normally SSS)
E   Day in week (e.g Monday, Tuesday etc.)
D   Day in year (1-366)
F   Day of week in month (e.g. 1st Thursday of December)
w   Week in year (1-53)
W   Week in month (0-5)
a   AM / PM marker
k   Hour in day (1-24, unlike HH's 0-23)
K   Hour in day, AM / PM (0-11)
z   Time Zone

1
虽然其他答案也是正确的,但我喜欢这个答案,因为它还有助于解决与时间相关的问题。谢谢@Vighnesh KM - Ankit Gupta

22

要获取当前日期和时间并以特定格式显示,可以使用以下代码:

Java语言

Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String strDate = sdf.format(c.getTime());
Log.d("Date", "DATE: " + strDate)

在Kotlin中

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    val current = LocalDateTime.now()
    val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy. HH:mm:ss")
    var myDate: String =  current.format(formatter)
    Log.d("Date", "DATE: " + myDate)
} else {
    var date = Date()
    val formatter = SimpleDateFormat("MMM dd yyyy HH:mma")
    val myDate: String = formatter.format(date)
    Log.d("Date", "DATE: " + myDate)
}

日期格式化程序模式
"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

2
感谢您想要做出贡献。您是否正在贡献一些之前36个答案中没有的东西?无论如何,您仍在使用臭名昭著且过时的SimpleDateFormat类。即使在Oreo之前,您也不需要这样做,而是可以使用ThreeTenABP,它是java.time的后移版本,是现代Java日期和时间API。 - Ole V.V.

17
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);

那只是一个不完整的答案。问题是:“如何获取当前的时间和日期?” - Peter Mortensen

16

这是一个有用的方法,可以获取日期和时间:

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;
}

您可以调用此方法获取当前日期和时间值:

2017/01//09 19:23

我不喜欢演示逻辑和过程逻辑的紧密耦合;我更喜欢一种只进行格式化并接受日期输入参数的方法。我也不明白为什么你要使用两个SimpleDateFormat和两个Date……难道你不能只使用“yyyy/MM/dd HH:mm”作为格式,并调用一次日历吗? - charles-allen

13

如果您需要当前日期:

Calendar cc = Calendar.getInstance();
int year = cc.get(Calendar.YEAR);
int month = cc.get(Calendar.MONTH);
int mDay = cc.get(Calendar.DAY_OF_MONTH);
System.out.println("Date", year + ":" + month + ":" + mDay);

如果您需要当前时间:

 int mHour = cc.get(Calendar.HOUR_OF_DAY);
 int mMinute = cc.get(Calendar.MINUTE);
 System.out.println("time_format" + String.format("%02d:%02d", mHour , mMinute));

12
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    System.out.println("time => " + dateFormat.format(cal.getTime()));

    String time_str = dateFormat.format(cal.getTime());

    String[] s = time_str.split(" ");

    for (int i = 0; i < s.length; i++) {
         System.out.println("date  => " + s[i]);
    }

    int year_sys = Integer.parseInt(s[0].split("/")[0]);
    int month_sys = Integer.parseInt(s[0].split("/")[1]);
    int day_sys = Integer.parseInt(s[0].split("/")[2]);

    int hour_sys = Integer.parseInt(s[1].split(":")[0]);
    int min_sys = Integer.parseInt(s[1].split(":")[1]);

    System.out.println("year_sys  => " + year_sys);
    System.out.println("month_sys  => " + month_sys);
    System.out.println("day_sys  => " + day_sys);

    System.out.println("hour_sys  => " + hour_sys);
    System.out.println("min_sys  => " + min_sys);

12

使用:

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

这将为您提供例如“12:32”的结果。

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


12

您也可以使用android.os.SystemClock。 例如,SystemClock.elapsedRealtime()会在手机休眠时提供更准确的时间读数。


11

您可以直接使用以下代码:

 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());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接