获取Android上的当前时间和日期

M7M*_*M7M 1058 time android date

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

小智 1233

你可以使用:

import java.util.Calendar

Date currentTime = Calendar.getInstance().getTime();
Run Code Online (Sandbox Code Playgroud)

日历中有很多常量可供您使用.

编辑:
检查日历类文档

  • 正如@adamdport所说,这实际上并没有回答这个问题......`Calendar.getInstance().getTime()`或`Calendar.getInstance().getTimeInMillis()`会起作用. (41认同)
  • +1这非常有帮助.作为新的,我们需要的所有这些小花絮......我正在使用日历来获得朱利安日期.比获得毫秒并弄清楚价值是否等于今天要容易得多;) (14认同)
  • @Kyle是的,它基于设备时间设置/时区.引自[doc](http://developer.android.com/reference/java/util/Calendar.html):*"Calendar的getInstance方法返回一个日历,其语言环境基于**系统设置**及其时间字段已使用当前日期和时间"* - (在类文档中的第一个样本代码行之上)进行初始化. (11认同)
  • 但这会从哪里拉出日期和时间?android设备设置本身? (8认同)
  • 这只是给我当前的第二个,介于0和60之间.过去几年有什么变化吗? (3认同)
  • +1此解决方案具有毫秒精度,正是我所需要的. (2认同)
  • 仅供参考,麻烦的旧日期时间类,例如java.util.Date,java.util.Calendar和java.text.SimpleDateFormat,现在已经被[java.time](https: //docs.oracle.com/javase/9​​/docs/api/java/time/package-summary.html)类。在[*** ThreeTen-Backport ***](http://www.threeten.org/threetenbp/)项目中,许多java.time功能都已反向移植到Java 6和Java 7。在[*** ThreeTenABP ***](https://github.com/JakeWharton/ThreeTenABP)项目中进一步适用于较早的Android。请参阅[*如何使用ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706)。 (2认同)

Tho*_*thy 484

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

Time now = new Time();
now.setToNow();
Run Code Online (Sandbox Code Playgroud)

从上面链接的参考:

Time类是java.util.Calendar和java.util.GregorianCalendar类的更快替代品.Time类的实例表示以第二精度指定的时刻.


注1: 我写这个答案已有好几年了,它是关于一个旧的,特定于Android的,现已弃用的类.谷歌现在 "他的班级有很多问题,建议改用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 ...
Run Code Online (Sandbox Code Playgroud)

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

  • @IgorZelaya如果你想要毫秒精度,你可能正在进行**间隔时间**,而不是一天中的时间.Android文档建议使用`SystemClock.uptimeMillis()`进行间隔计时.由于这是大多数内置函数所使用的,因此有很强的动机可以在所有设备上实现良好.请参阅[SystemClock]中的讨论(http://developer.android.com/reference/android/os/SystemClock.html)...如果您想将其与时间相关联,请在app的onResume中,同时阅读此内容,以及时间/ setToNow/toMillis.记住那些之间的区别. (3认同)
  • @InsanityOnABun和Muhammad Babar.不不不.文档说**"以第二精度指定"**即使是最简单的测试(在循环中获取当前时间,到米利斯,以及记录/打印结果)也会向您显示结果时间以毫秒为单位! (2认同)

Mic*_*ash 339

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

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
String currentDateandTime = sdf.format(new Date());
Run Code Online (Sandbox Code Playgroud)

  • 简而言之:`String currentDateandTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());` (28认同)
  • 请注意,如果性能存在问题,SimpleDateFormat可能会出现问题.在我的应用程序中,我有一个自定义视图,其中包含大约20个HH:MM标签,表示特定时间(长整数保持毫秒),以及相同数量的可绘制资源.初步测试表明,这种相互作用并不像我想要的那么流畅.当我在onDraw()上进行分析时,我发现SimpleTimeFormatter调用占用了80%的时间.事实上,我正在阅读此页面,作为搜索更高效格式化程序的一部分,并了解有关日历等的更多信息. (9认同)
  • 你可以在中间插入`sdf.setTimeZone(TimeZone.getDefault())` (4认同)
  • 是的,但不再.我没有意识到所涉及的开销,并认为它几乎是一个POJO. (3认同)

ANe*_*ati 222

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

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

而您可以使用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
Run Code Online (Sandbox Code Playgroud)


kan*_*eda 126

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

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

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

UPDATE

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

这个类有很多问题,建议使用GregorianCalendar代替.

已知的问题:

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


小智 78

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

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());
Run Code Online (Sandbox Code Playgroud)

哪个输出:

Feb 27, 2012 5:41:23 PM
Run Code Online (Sandbox Code Playgroud)

  • 根据Android API,这是推荐的方法。http://developer.android.com/reference/java/text/DateFormat.html#getDateTimeInstance()谢谢! (2认同)

Ami*_*rma 58

尝试这种方式下面给出所有格式以获取日期和时间格式.

    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);
Run Code Online (Sandbox Code Playgroud)

第一

第二 第三


Jos*_*phL 49

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

Date currentDate = new Date(System.currentTimeMillis());
Run Code Online (Sandbox Code Playgroud)

而正如别人所说,创造时间

Time currentTime = new Time();
currentTime.setToNow();
Run Code Online (Sandbox Code Playgroud)

  • 不需要`System.currentTimeMillis()`; 只需`new Date()`[做同样的事情](http://docs.oracle.com/javase/7/docs/api/java/util/Date.html#Date()). (13认同)

Bas*_*que 38

TL;博士

Instant.now()  // Current moment in UTC.
Run Code Online (Sandbox Code Playgroud)

…要么…

ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )  // In a particular time zone
Run Code Online (Sandbox Code Playgroud)

细节

其他答案虽然正确,但已经过时了.旧的日期时间类已被证明设计糟糕,令人困惑,并且很麻烦.

java.time

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

这些新课程的灵感来自于由JSR 310定义并由ThreeTen-Extra项目扩展的非常成功的Joda-Time项目.

请参阅Oracle教程.

Instant

An InstantUTC时间轴上的一个时刻,分辨率高达纳秒.

 Instant instant = Instant.now(); // Current moment in UTC.
Run Code Online (Sandbox Code Playgroud)

时区

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

使用正确的时区的名称,格式continent/regionAmerica/Montreal,Europe/BrusselsAsia/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 );
Run Code Online (Sandbox Code Playgroud)

生成字符串

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

ISO 8601

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

String output = instant.toString();
Run Code Online (Sandbox Code Playgroud)

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" );
Run Code Online (Sandbox Code Playgroud)

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

formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );
Run Code Online (Sandbox Code Playgroud)

本地化

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

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

关于java.time

java.time框架是建立在Java 8和更高版本.这些类取代麻烦的老传统日期时间类,如java.util.Date,Calendar,和SimpleDateFormat.

现在处于维护模式Joda-Time项目建议迁移到java.time类.

要了解更多信息,请参阅Oracle教程.并搜索Stack Overflow以获取许多示例和解释.规范是JSR 310.

您可以直接与数据库交换java.time对象.使用符合JDBC 4.2或更高版本的JDBC驱动程序.不需要字符串,不需要课程.java.sql.*

从哪里获取java.time类?

ThreeTen-额外项目与其他类扩展java.time.该项目是未来可能添加到java.time的试验场.您可以在此比如找到一些有用的类Interval,YearWeek,YearQuarter,和更多.

  • @giraffe.guru 重读我的答案。你错过了第三颗子弹。大部分 java.time 功能在 [ThreeTen-Backport](http://www.threeten.org/threetenbp/) 中向后移植到 Java 6 和 7,并在 [ThreeTenABP](https://www.threeten.org/threetenbp/) 中进一步适应 Android github.com/JakeWharton/ThreeTenABP)。 (2认同)
  • @Ryde 正如我对 giraffe.guru 所说的,重读我的答案。寻找提到“Android”的第三个项目符号。 (2认同)

Him*_*wal 35

您可以使用以下代码:

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

输出:

2014-11-11 00:47:55
Run Code Online (Sandbox Code Playgroud)

您还可以SimpleDateFormat此处获得更多格式选项.


Ska*_*ate 32

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

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);
Run Code Online (Sandbox Code Playgroud)

日期相同,如下:

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);
Run Code Online (Sandbox Code Playgroud)


eLo*_*ato 25

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

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

// textView is the TextView view that should display it
textView.setText(currentDateTimeString);
Run Code Online (Sandbox Code Playgroud)

  • 根据Date()参考文档(http://developer.android.com/reference/java/util/Date.html),没有引用不推荐使用的Date()类 - 但是不推荐使用多个方法和构造函数. (11认同)
  • 你应该使用`Calendar`或`GregorianCalendar`."Date"类已弃用. (8认同)
  • 这将在当前用户设置意义上产生不正确的结果(例如,12/24时间格式).使用android.text.format.DateFormat.getTimeFormat(Context context)获取当前用户设置的DateFormat. (2认同)

Vig*_* KM 24

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
Run Code Online (Sandbox Code Playgroud)

日期格式模式

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
Run Code Online (Sandbox Code Playgroud)


Ale*_*thi 16

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);
Run Code Online (Sandbox Code Playgroud)


Jor*_*sys 14

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

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;
}
Run Code Online (Sandbox Code Playgroud)

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

2017/01//09 19:23
Run Code Online (Sandbox Code Playgroud)


小智 12

Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour+":"+time.minute);
Run Code Online (Sandbox Code Playgroud)

例如,这将给你12:32.

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


dug*_*ggu 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);
Run Code Online (Sandbox Code Playgroud)


小智 11

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


小智 10

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);
Run Code Online (Sandbox Code Playgroud)

输出

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);
Run Code Online (Sandbox Code Playgroud)


Oma*_*nik 9

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

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

输出如下格式:2015-06-18T10:15:56-05:00


Rej*_*ran 9

如果您需要当前日期,

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);
Run Code Online (Sandbox Code Playgroud)

如果你需要当前时间,

 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 ));
Run Code Online (Sandbox Code Playgroud)


Vip*_*ati 9

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

在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)
Run Code Online (Sandbox Code Playgroud)

在科特林

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)
}
Run Code Online (Sandbox Code Playgroud)

日期格式化程序模式

"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
Run Code Online (Sandbox Code Playgroud)

  • 感谢您希望共同贡献。您是否贡献了之前 36 个答案中尚未包含的内容?无论如何,您仍在使用众所周知的麻烦且过时的“SimpleDateFormat”类。即使在 Oreo 之前,您也不需要这样做,您也可以使用 [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP),它是 java.time(现代 Java 日期和时间 API)的向后移植。 (2认同)

The*_*Man 8

Time now = new Time();
now.setToNow();
Run Code Online (Sandbox Code Playgroud)

试试这个也适合我.


Muh*_*Ali 8

Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();
Run Code Online (Sandbox Code Playgroud)

  • [getDate](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#getDay--)、[getHours](https://docs.oracle. com/javase/8/docs/api/java/util/Date.html#getHours--) 等说***“已弃用”。***。例如,*“从 JDK 1.1 版开始,由 Calendar.get(Calendar.HOUR_OF_DAY) 替换。”*。JDK 1.1 版于 ***February 1997 ***(!!!) 发布 - 在发布此答案时已弃用 16 年。 (2认同)

Ann*_*lle 8

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

Time t = new Time(Time.getCurrentTimezone());
t.setToNow();
String date = t.format("%Y/%m/%d");
Run Code Online (Sandbox Code Playgroud)

这将以一个很好的形式给你一个结果,如在这个例子中:"2014/02/09".


Ali*_*aee 7

您只需使用以下代码:

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

 DateFormat df1=new SimpleDateFormat("yyyy/MM/dd");//foramt date
 String date=df1.format(Calendar.getInstance().getTime());
Run Code Online (Sandbox Code Playgroud)


Öme*_*ğit 7

爪哇

Long date=System.currentTimeMillis();
SimpleDateFormat dateFormat =new SimpleDateFormat("dd / MMMM / yyyy - HH:mm", Locale.getDefault());
String dateStr = dateFormat.format(date);
Run Code Online (Sandbox Code Playgroud)

科特林

日期(毫秒和 13 位数字)(十六进制至今)

val date=System.currentTimeMillis() //here the date comes in 13 digits
val dtlong = Date(date)
val sdfdate = SimpleDateFormat(pattern, Locale.getDefault()).format(dtlong)
Run Code Online (Sandbox Code Playgroud)

日期格式化程序

"dd / MMMM / yyyy - HH:mm" -> 29 / April / 2022 - 12:03 
"dd / MM / yyyy" -> 29 / 03 / 2022
"dd / MMM / yyyy" -> 29 / Mar / 2022 (shortens the month) 
"EEE, d MMM yyyy HH:mm:ss" -> Wed, 4 Jul 2022 12:08:56
Run Code Online (Sandbox Code Playgroud)


小智 6

好吧,我的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);
Run Code Online (Sandbox Code Playgroud)

输出:03:25 PM - 2017/10/03


Aks*_*wal 5

您应该根据新的 API 使用 Calender 类。Date现已弃用。

Calendar cal = Calendar.getInstance();

String date = "" + cal.get(Calendar.DATE) + "-" + (cal.get(Calendar.MONTH)+1) + "-" + cal.get(Calendar.YEAR);

String time = "" + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE);
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试这个

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


Dan*_*ger 5

下面的方法将返回String中的当前日期和时间,根据您的实际时区使用不同的时区。我已经使用了GMT

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);
}
Run Code Online (Sandbox Code Playgroud)


Aya*_*han 5

尝试以简单的方式获取当前日期和时间:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
String currentDateandTime = sdf.format(new Date());
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述