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

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


#1楼

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

#2楼

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

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

#3楼

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

尝试一下对我也有用。


#4楼

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

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

记住要导入android.text.format.Time;


#5楼

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

#6楼

Date todayDate = new Date();
todayDate.getDay();
todayDate.getHours();
todayDate.getMinutes();
todayDate.getMonth();
todayDate.getTime();

#7楼

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

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

#8楼

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

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

这将以一种不错的形式为您提供结果,例如以下示例:“ 2014/02/09”。


#9楼

您可以使用以下代码:

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

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


#10楼

您应该根据新的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);

#11楼

试试这个代码,它显示当前日期和时间

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

#12楼

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

    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


#13楼

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

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

第一

第二 第三


#14楼

尝试这个

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

#15楼

tl; dr

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

…要么…

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

细节

其他答案虽然正确,但已过时。 事实证明,旧的日期时间类设计不良,令人困惑且麻烦。

java.time

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

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

请参阅《 Oracle教程》

Instant

InstantUTC时间线上的时刻,分辨率高达纳秒

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

时区

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

使用continent/region格式的正确时区名称 ,例如America/MontrealEurope/BrusselsAsia/Kolkata 。 切勿使用ESTIST等3-4个字母的缩写,因为它们既不是标准化的也不是唯一的。

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

Java中的日期时间类型表(现代和旧式)

产生字串

您可以轻松地生成一个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" );

指定人类语言(英语, 法语等)的语言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和Android的哪个版本上使用* java.time *技术的哪种实现。

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

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

要了解更多信息,请参见Oracle教程 。 并在Stack Overflow中搜索许多示例和说明。 规格为JSR 310

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

在哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。 该项目为将来可能在java.time中添加内容提供了一个试验场。 您可以在这里找到一些有用的类,比如IntervalYearWeekYearQuarter ,和更多


#16楼

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

#17楼

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

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

#18楼

如果您需要当前日期,

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

#19楼

这是获取日期和时间的有用方法:

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

#20楼

下面的方法将以字符串形式返回当前日期和时间,根据您的实际时区使用不同的时区。我已经使用了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);
}

#21楼

好吧,我在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


#22楼

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

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

根据上面链接的参考:

Time类可以更快地替换java.util.Calendar和java.util.GregorianCalendar类。 Time类的实例表示时刻,以秒精度指定。


注意1:自从我写了这个答案已经好几年了,它是关于一个旧的,特定于Android的类,现在已弃用的类。 Google现在 “他的课程有很多问题,建议改用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将开始重复。


#23楼

有几种选择,因为Android主要是Java,但是如果您希望在textView中编写它,则以下代码可以解决问题:

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

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

#24楼

您可以使用:

import java.util.Calendar

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

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

编辑:
查看日历类文档


#25楼

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

在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

#26楼

您还可以使用android.os.SystemClock。 例如,SystemClock.elapsedRealtime()将在电话进入睡眠状态时为您提供更准确的时间读数。


#27楼

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

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

并像别人提到的那样创造了时间

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

#28楼

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

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

#29楼

实际上,使用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类。

更新

正如许多人指出的那样,Google表示此类存在许多问题,因此不应再使用:

此类有很多问题,建议改用GregorianCalendar。

已知的问题:

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


#30楼

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

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

哪个输出:

Feb 27, 2012 5:41:23 PM
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值