你可以使用:
import java.util.Calendar
Date currentTime = Calendar.getInstance().getTime();
日历中有很多常量可以满足您的一切需求。
检查 Calendar class documentation。
您可以(但不再应该 - 见下文!)使用 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
将开始重复。
SystemClock.uptimeMillis()
进行间隔计时。由于这是大多数内置函数所使用的,因此有强烈的动机让它在所有设备上得到很好的实现。请参阅 SystemClock 中的讨论...如果您想将其与一天中的时间相关联,请在应用程序的 onResume 中阅读此内容和 Time/setToNow/toMillis。记住它们之间的区别。
GregorianCalendar
几年前在 Java 和后来的 Android 中被 java.time 类取代,特别是 ZonedDateTime
。对于早期的 Android,请参阅 ThreeTen-Backport 和 ThreeTenABP 项目。
如果要以特定模式获取日期和时间,可以使用以下命令:
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());
onDraw()
中创建了 SimpleDateFormat
的新实例?
String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
sdf.setTimeZone(TimeZone.getDefault())
对于那些可能更喜欢自定义格式的人,您可以使用:
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
实际上,使用 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 脚本一起使用。
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。
立即的
Instant
是 UTC 中时间轴上的一个时刻,分辨率最高为 nanoseconds。
Instant instant = Instant.now(); // Current moment in UTC.
时区
应用时区 (ZoneId
) 以获得 ZonedDateTime
。如果省略时区,则会隐式应用 JVM 当前的默认时区。最好明确指定所需/预期的时区。
以 continent/region
的格式使用 proper time zone names,例如 America/Montreal
、Europe/Brussels
或 Asia/Kolkata
。切勿使用 3-4 个字母的缩写,例如 EST
或 IST
,因为它们既不标准化也不独特。
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
请注意,对于 ZonedDateTime
,toString
方法通过在方括号中附加时区名称来扩展 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.Date
、Calendar
和 & 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
Instant.now()
和 ZonedDateTime.now()
是必需的 API 26
对于当前日期和时间,使用:
String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
哪个输出:
Feb 27, 2012 5:41:23 PM
尝试以下方式。下面给出了所有格式以获取日期和时间格式。
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
要获取当前时间,您可以使用 Java 中的标准 System.currentTimeMillis()
。然后你可以用它来创建一个日期
Date currentDate = new Date(System.currentTimeMillis());
和其他人提到的创造时间
Time currentTime = new Time();
currentTime.setToNow();
Cannot resolve constructor Date()
在 android 中,Android SDK 混合使用 Java 6 和 7。
new Date(System.currentTimeMillis())
不正确:(a) 它是多余的,因为它与 new Date()
完全相同。 (b) 从 Java 8 及更高版本开始,麻烦的 java.util.Date
类现在被 java.time.Instant
取代。向后移植到 Java 6 & ThreeTen-Backport 项目中的 7,以及 ThreeTenABP 中的早期 Android (<26)。
您可以使用以下代码:
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.Date
、java.util.Calendar
和 java.text.SimpleDateFormat
等麻烦的旧日期时间类现在是 legacy,被 Java 8 及更高版本中内置的 java.time 类所取代。见Tutorial by Oracle。
简单的。您可以剖析时间以获取当前时间的单独值,如下所示:
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);
有几个选项,因为 Android 主要是 Java,但如果你想在 textView 中编写它,下面的代码就可以了:
String currentDateTimeString = DateFormat.getDateInstance().format(new Date());
// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
Calendar
或 GregorianCalendar
。 Date
类已弃用。
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
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);
对于具有格式的当前日期和时间,请使用:
在 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
SimpleDateFormat
类。甚至在不需要 Oreo 之前,您也可以改用 ThreeTenABP,它是现代 Java 日期和时间 API java.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;
}
您可以调用此方法并获取当前日期和时间值:
2017/01//09 19:23
SimpleDateFormat
s & 2 Date
s...你不能只使用 "yyyy/MM/dd HH:mm"
作为格式 &调用日历一次?
如果您需要当前日期:
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));
您也可以使用 android.os.SystemClock。例如 SystemClock.elapsedRealtime() 将在手机处于睡眠状态时为您提供更准确的时间读数。
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);
利用:
Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour + ":" + time.minute);
例如,这将为您提供“12:32”。
请记住import android.text.format.Time;
。
您可以简单地使用以下代码:
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());
对于自定义的时间和日期格式:
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
Time now = new Time();
now.setToNow();
试试这个也对我有用。
您可以使用以下方法获取日期:
Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date = t.format("%Y/%m/%d");
这将为您提供一个很好的结果,如本例所示:“2014/02/09”。
Time t = new Time();
将使用默认时区。根据我的经验,默认 == 当前。
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
好吧,我对 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
Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();
尝试这个
String mytime = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
以下方法将以字符串形式返回当前日期和时间,根据您的实际时区使用不同的时区。我用过格林威治标准时间。
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);
}
尝试使用以下代码:
Date date = new Date();
SimpleDateFormat dateFormatWithZone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",Locale.getDefault());
String currentDate = dateFormatWithZone.format(date);
Calendar.getInstance().getTime()
或Calendar.getInstance().getTimeInMillis()
会起作用。