ChatGPT解决这个技术问题 Extra ChatGPT

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

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

43个答案!虽然其中许多在编写时都很好,但在 2018 年使用的最佳答案是 here

P
Peter Mortensen

你可以使用:

import java.util.Calendar

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

日历中有很多常量可以满足您的一切需求。

检查 Calendar class documentation


+1 这非常有帮助。作为新的,这是我们需要的所有这些小花絮......我正在使用日历来获取朱利安日期。比获取毫秒数并确定值是否等于今天要容易得多;)
但这从哪里拉出日期和时间呢? android设备设置本身?
@Kyle 是的,它基于设备时间设置/时区。引用 doc“Calendar 的 getInstance 方法返回一个日历,其区域设置基于 系统设置,并且其时间字段已使用当前日期和时间初始化” - (在类文档的第一个示例代码行上方)。
这只是给了我当前的秒数,介于 0 到 60 之间。过去几年有什么变化吗?
正如@adamdport 所说,这实际上并不能回答问题...... Calendar.getInstance().getTime()Calendar.getInstance().getTimeInMillis() 会起作用。
T
Thomas Padron-McCarthy

您可以(但不再应该 - 见下文!)使用 android.text.format.Time

Time now = new Time();
now.setToNow();

从上面链接的参考资料:

Time 类是 java.util.Calendar 和 java.util.GregorianCalendar 类的更快替代品。 Time 类的一个实例表示时间中的一个时刻,以秒精度指定。

注意 1: 我写这个答案已经好几年了,它是关于一个旧的、特定于 Android 的、现已弃用的类。 Google 现在says说“[t]他的课程有很多问题,建议改用 GregorianCalendar”。

注意 2: 尽管 Time 类有一个 toMillis(ignoreDaylightSavings) 方法,但这只是为了方便传递给期望时间以毫秒为单位的方法。时间值只精确到一秒;毫秒部分始终为 000。如果在一个循环中你这样做

Time time = new Time();   time.setToNow();
Log.d("TIME TEST", Long.toString(time.toMillis(false)));
... do something that takes more than one millisecond, but less than one second ...

结果序列将重复相同的值,例如 1410543204000,直到下一秒开始,此时 1410543205000 将开始重复。


@InsanityOnABun 和穆罕默德巴巴尔。不不不。文档说“以秒精度指定”即使是最简单的测试(在循环中获取当前时间、toMillis 并记录/打印结果)也会向您显示结果时间的毫秒部分为 000!
@IgorZelaya 如果您想要毫秒精度,您可能正在执行间隔计时,而不是一天中的时间。 Android 文档建议使用 SystemClock.uptimeMillis() 进行间隔计时。由于这是大多数内置函数所使用的,因此有强烈的动机让它在所有设备上得到很好的实现。请参阅 SystemClock 中的讨论...如果您想将其与一天中的时间相关联,请在应用程序的 onResume 中阅读此内容和 Time/setToNow/toMillis。记住它们之间的区别。
Do not use the Time class。将来它将被删除,并且存在许多问题。
>此类在 API 级别 22 中已弃用。请改用 GregorianCalendar。请参阅here
实际上,GregorianCalendar 几年前在 Java 和后来的 Android 中被 java.time 类取代,特别是 ZonedDateTime。对于早期的 Android,请参阅 ThreeTen-BackportThreeTenABP 项目。
A
Ankush Chauhan

如果要以特定模式获取日期和时间,可以使用以下命令:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());

或者,

日期:

String currentDate = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(new Date());

时间:

String currentTime = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date());

请注意,如果性能有问题,SimpleDateFormat 可能会出现问题。在我的应用程序中,我有一个自定义视图,它有大约 20 个 HH:MM 标签,代表特定时间(长整数保持毫秒),以及相同数量的可绘制资源。最初的测试表明交互并不像我想要的那样流畅。当我分析 onDraw() 时,我发现 SimpleTimeFormatter 调用占用了 80% 的时间。事实上,我阅读此页面是为了寻找更有效的格式化程序并了解有关日历等的更多信息。
@William T. Mallard:您是否在 onDraw() 中创建了 SimpleDateFormat 的新实例?
是的,但不再是。我没有意识到所涉及的开销,并认为这几乎是一个 POJO。
简而言之:String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
您可以在中间插入 sdf.setTimeZone(TimeZone.getDefault())
P
Peter Mortensen

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

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

正确格式的最佳答案。做得好
k
kaneda

实际上,使用 Time.getCurrentTimezone() 设置设备上设置的当前时区更安全,否则您将获得 UTC 的当前时间。

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();

然后,您可以获得所需的所有日期字段,例如:

textViewDay.setText(today.monthDay + "");             // Day of the month (1-31)
textViewMonth.setText(today.month + "");              // Month (0-11)
textViewYear.setText(today.year + "");                // Year 
textViewTime.setText(today.format("%k:%M:%S"));  // Current time

有关所有详细信息,请参阅 android.text.format.Time 类。

更新

正如许多人指出的那样,谷歌说这个类有很多问题,不应该再使用了:

这个类有很多问题,建议改用 GregorianCalendar。已知问题:由于历史原因,在执行时间计算时,当前所有算术都使用 32 位整数进行。这限制了从 1902 年到 2037 年可表示的可靠时间范围。有关详细信息,请参阅有关 2038 年问题的维基百科文章。不要依赖这种行为;将来可能会改变。在不存在的日期调用 switchTimezone(String),例如由于 DST 转换而跳过的挂钟时间,将导致日期为 1969 年(即 -1,或 1970 年 1 月 1 日 UTC 前 1 秒)。大部分格式化/解析都假定 ASCII 文本,因此不适合与非 ASCII 脚本一起使用。


时间应该从哪个包中导入?
此类在 API 级别 22 中已弃用。我们可以改用 GregorianCalendar。
P
Peter Mortensen

tl;博士

Instant.now()  // Current moment in UTC.

…或者…

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone

细节

其他答案虽然正确,但已过时。旧的日期时间类已被证明设计不佳、混乱且麻烦。

java.time

那些旧类已被 java.time 框架取代。

Java 8 及更高版本:java.time 框架是内置的。

Java 7 & 6:使用 java.time 的反向移植。

Android:使用该反向移植的包装版本。

这些新类的灵感来自非常成功的 Joda-Time 项目,由 JSR 310 定义并由 ThreeTen-Extra 项目扩展。

请参阅 Oracle Tutorial

立即的

InstantUTC 中时间轴上的一个时刻,分辨率最高为 nanoseconds

 Instant instant = Instant.now(); // Current moment in UTC.

时区

应用时区 (ZoneId) 以获得 ZonedDateTime。如果省略时区,则会隐式应用 JVM 当前的默认时区。最好明确指定所需/预期的时区。

continent/region 的格式使用 proper time zone names,例如 America/MontrealEurope/BrusselsAsia/Kolkata。切勿使用 3-4 个字母的缩写,例如 ESTIST,因为它们既不标准化也不独特。

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

https://i.stack.imgur.com/8VSjJ.png

生成字符串

您可以轻松生成 String 作为日期时间值的文本表示。您可以使用标准格式、您自己的自定义格式或自动本地化格式。

ISO 8601

您可以调用 toString 方法来获取使用通用且合理的 ISO 8601 标准格式化的文本。

String output = instant.toString();

2016-03-23T03:09:01.613Z

请注意,对于 ZonedDateTimetoString 方法通过在方括号中附加时区名称来扩展 ISO 8601 标准。非常有用和重要的信息,但不是标准的。

2016-03-22T20:09:01.613-08:00[美国/洛杉矶]

自定义格式

或者使用 DateTimeFormatter 类指定您自己的特定格式模式。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );

为人类语言(英语、French 等)指定 Locale,以用于翻译日/月名称以及定义文化规范,例如年月顺序和日期。请注意,Locale 与时区无关。

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );

本地化

更好的是,让 java.time 自动完成本地化工作。

DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) );  // Or Locale.CANADA_FRENCH and so on.

关于 java.time

java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendar 和 & SimpleDateFormat

要了解更多信息,请参阅 Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

Joda-Time 项目现在位于 maintenance mode 中,建议迁移到 java.time 类。

您可以直接与您的数据库交换 java.time 对象。使用符合 JDBC 4.2 或更高版本的 JDBC driver。不需要字符串,不需要 java.sql.* 类。休眠 5 和JPA 2.2 支持 java.time

在哪里可以获得 java.time 类?

Java SE 8、Java SE 9、Java SE 10、Java SE 11 及更高版本 - 标准 Java API 的一部分,具有捆绑的实现。 Java 9 带来了一些小功能和修复。

Java 9 带来了一些小功能和修复。

Java SE 6 和 Java SE 7 大多数 java.time 功能在 ThreeTen-Backport 中向后移植到 Java 6 和 7。

大多数 java.time 功能在 ThreeTen-Backport 中向后移植到 Java 6 和 7。

Android 更高版本的 Android (26+) 捆绑了 java.time 类的实现。对于早期的 Android (<26),API 脱糖过程带来了最初未内置于 Android 中的 java.time 功能的子集。如果脱糖不能提供您所需要的,ThreeTenABP 项目会将 ThreeTen-Backport(上面提到的)适配到 Android。请参阅如何使用 ThreeTenABP……。

更高版本的 Android (26+) 捆绑了 java.time 类的实现。

对于早期的 Android (<26),API 脱糖过程带来了最初未内置于 Android 中的 java.time 功能的子集。如果脱糖不能提供您所需要的,ThreeTenABP 项目会将 ThreeTen-Backport(上面提到的)适配到 Android。请参阅如何使用 ThreeTenABP……。

如果脱糖不能提供您所需要的,ThreeTenABP 项目会将 ThreeTen-Backport(上面提到的)适配到 Android。请参阅如何使用 ThreeTenABP……。

https://i.stack.imgur.com/Sksw9.png


@giraffe.guru 重读我的答案。你错过了第三颗子弹。大部分 java.time 功能都向后移植到 Java 6 & ThreeTen-Backport 中的 7 并在 ThreeTenABP 中进一步适应 Android。
Instant.now()ZonedDateTime.now() 是必需的 API 26
@Ryde 正如我对 giraffe.guru 所说,重读我的答案。寻找提到“Android”的第三个项目符号。
我相信你是对的:你的新 java.time 版本表比项目符号列表更直接、更容易地传达信息。如果那是我,我想我会把事情复杂化一点,并在 ThreeTenBackport/Java 8+ 和 ThreeTenABP/Android 26+ 下的括号(或类似的东西)中打上复选标记,因为这些组合确实有效,只有使用它们通常没有任何意义。正在开发的 Android 应用程序使用 ThreeTenABP 并针对 26 级以上和以下的一系列 Android API 级别。在我看来,开发人员在这些情况下选择得很好。
@OleV.V.感谢您建议在图形表中使用辅助复选标记。我一直在表的更高版本中使用它。大有改善。
P
Peter Mortensen

对于当前日期和时间,使用:

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

哪个输出:

Feb 27, 2012 5:41:23 PM

我得到了系统的当前日期、日期和时间,但时间没有改变。我想以秒为单位增加时间。我该怎么办?
根据 Android API,这是推荐的方法:developer.android.com/reference/java/text/…谢谢!
P
Peter Mortensen

尝试以下方式。下面给出了所有格式以获取日期和时间格式。

    Calendar c = Calendar.getInstance();
    SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa");
    String datetime = dateformat.format(c.getTime());
    System.out.println(datetime);

https://i.stack.imgur.com/gF7wz.png

https://i.stack.imgur.com/tSpkg.png

https://i.stack.imgur.com/ppQAf.png


J
JosephL

要获取当前时间,您可以使用 Java 中的标准 System.currentTimeMillis()。然后你可以用它来创建一个日期

Date currentDate = new Date(System.currentTimeMillis());

和其他人提到的创造时间

Time currentTime = new Time();
currentTime.setToNow();

不需要System.currentTimeMillis();只需 new Date() does the same thing
@Jonik Cannot resolve constructor Date() 在 android 中,Android SDK 混合使用 Java 6 和 7。
@mghhgm 不,new Date(System.currentTimeMillis()) 不正确:(a) 它是多余的,因为它与 new Date() 完全相同。 (b) 从 Java 8 及更高版本开始,麻烦的 java.util.Date 类现在被 java.time.Instant 取代。向后移植到 Java 6 & ThreeTen-Backport 项目中的 7,以及 ThreeTenABP 中的早期 Android (<26)。
H
Himanshu Aggarwal

您可以使用以下代码:

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

输出:

2014-11-11 00:47:55

您还可以从 here 获得更多用于 SimpleDateFormat 的格式选项。


仅供参考,诸如 java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在是 legacy,被 Java 8 及更高版本中内置的 java.time 类所取代。见Tutorial by Oracle
P
Peter Mortensen

简单的。您可以剖析时间以获取当前时间的单独值,如下所示:

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 您为此使用日期
P
Peter Mortensen

有几个选项,因为 Android 主要是 Java,但如果你想在 textView 中编写它,下面的代码就可以了:

String currentDateTimeString = DateFormat.getDateInstance().format(new Date());

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);

您应该使用 CalendarGregorianCalendarDate 类已弃用。
谢谢队友 :) 我对此一无所知
根据 Date() 参考文档 (developer.android.com/reference/java/util/Date.html),没有任何内容提到不推荐使用 Date() 类 - 但是不推荐使用几种方法和构造函数。
这将在当前用户设置的意义上产生不正确的结果(例如 12/24 时间格式)。使用 android.text.format.DateFormat.getTimeFormat(Context context) 获取当前用户设置的 DateFormat。
@Zac 你是对的,即使是 Date 的 getTime 方法也更充分
P
Peter Mortensen
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

尽管其他答案也是正确的。我喜欢这个答案,因为它也有助于解决与时间相关的问题。谢谢@Vighnesh KM
P
Peter Mortensen
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);

这只是一半的答案。问题是“我怎样才能得到当前的时间和日期?”
P
Peter Mortensen

对于具有格式的当前日期和时间,请使用:

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

在科特林

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

感谢您希望共同贡献。您是否提供了之前 36 个答案中尚未提供的内容?无论如何,您仍在使用臭名昭著的麻烦且早已过时的 SimpleDateFormat 类。甚至在不需要 Oreo 之前,您也可以改用 ThreeTenABP,它是现代 Java 日期和时间 API java.time 的向后移植。
J
Jorgesys

这是一种用于获取日期和时间的方法:

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

我不喜欢表示逻辑和流程逻辑的紧密耦合;我更喜欢一种只进行格式化的方法接受日期输入参数。我也不明白你为什么要使用 2SimpleDateFormats & 2 Dates...你不能只使用 "yyyy/MM/dd HH:mm" 作为格式 &调用日历一次?
M
Manaus

如果您需要当前日期:

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

Q
Quadroid

您也可以使用 android.os.SystemClock。例如 SystemClock.elapsedRealtime() 将在手机处于睡眠状态时为您提供更准确的时间读数。


P
Peter Mortensen
    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);

P
Peter Mortensen

利用:

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

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

请记住import android.text.format.Time;


P
Peter Mortensen

您可以简单地使用以下代码:

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

P
Peter Mortensen

对于自定义的时间和日期格式:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ",Locale.ENGLISH);
String cDateTime = dateFormat.format(new Date());

输出格式如下:

2015-06-18T10:15:56-05:00


日期类 was deprecated in 1997
J
Jibran Khan
Time now = new Time();
now.setToNow();

试试这个也对我有用。


P
Peter Mortensen

您可以使用以下方法获取日期:

Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date = t.format("%Y/%m/%d");

这将为您提供一个很好的结果,如本例所示:“2014/02/09”。


无参数构造函数 Time t = new Time(); 将使用默认时区。根据我的经验,默认 == 当前。
P
Peter Mortensen

Android 中的当前时间和日期,格式为

Calendar c = Calendar.getInstance();
System.out.println("Current dateTime => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate = df.format(c.getTime());
System.out.println("Format dateTime => " + formattedDate);

输出

I/System.out: Current dateTime => Wed Feb 26 02:58:17 GMT+05:30 2020
I/System.out: Format dateTime => 26-02-2020 02:58:17 AM

P
Peter Mortensen

好吧,我对 API 的一些答案有疑问,所以我融合了这段代码:

Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date1 = t.format("%Y/%m/%d");

Date date = new Date(System.currentTimeMillis());
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm aa", Locale.ENGLISH);
String var = dateFormat.format(date);
String horafecha = var+ " - " + date1;

tvTime.setText(horafecha);

输出:

03:25 PM - 2017/10/03

M
Muhammad Aamir Ali
Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();

seems to work - “分配一个 Date 对象并对其进行初始化,以便它表示分配它的时间,精确到毫秒。”。但是为什么在过去的 16 个答案中没有超过 2 年?似乎太容易了。它真的适用于Android吗?它是否在更高版本的 Android 中可用?
Another answer“Date 类已 弃用 现在。”A comment“您应该使用 Calendar 或 GregorianCalendar。Date 类已 已弃用。”
getDategetHours 等的文档说 “已弃用。”。例如,“从 JDK 版本 1.1 开始,由 Calendar.get(Calendar.HOUR_OF_DAY) 取代。”。 JDK 1.1 版于 1997 年 2 月 ***(!!!) 发布-发布此答案时已弃用 16 年。
A
Abhinaw Kumar

尝试这个

String mytime = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());

这是一个完美的衬里和优雅的解决方案。这就是所需要的,而不是像其他答案那样不必要的长解决方案。
java.util.Date 类 was deprecated in 1997
P
Peter Mortensen

以下方法将以字符串形式返回当前日期和时间,根据您的实际时区使用不同的时区。我用过格林威治标准时间。

public static String GetToday(){
    Date presentTime_Date = Calendar.getInstance().getTime();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return dateFormat.format(presentTime_Date);
}

P
Peter Mortensen

尝试使用以下代码:

 Date date = new Date();
 SimpleDateFormat dateFormatWithZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault());  
 String currentDate = dateFormatWithZone.format(date);