如何在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 formatint hour = cal.get(Calendar.HOUR);//24 hour formatint 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框架取代。
- Java 8和更高版本: java.time框架是内置的。
- Java 7和6:使用java.time的反向端口 。
- Android:使用该backport的此包装版本 。
这些新类的灵感来自由 JSR 310定义并由ThreeTen-Extra项目扩展的非常成功的Joda-Time项目。
请参阅《 Oracle教程》 。
Instant
Instant
是UTC时间线上的时刻,分辨率高达纳秒 。
Instant instant = Instant.now(); // Current moment in UTC.
时区
应用时区( ZoneId
)以获取ZonedDateTime
。 如果省略时区,则将隐式应用JVM的当前默认时区。 最好明确指定所需/预期的时区。
使用continent/region
格式的正确时区名称 ,例如America/Montreal
, Europe/Brussels
或Asia/Kolkata
。 切勿使用EST
或IST
等3-4个字母的缩写,因为它们既不是标准化的也不是唯一的。
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
产生字串
您可以轻松地生成一个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" );
指定人类语言(英语, 法语等)的语言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及更高版本中。 这些类取代了麻烦的旧的旧式日期时间类,例如java.util.Date
, Calendar
和SimpleDateFormat
。
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
要了解更多信息,请参见Oracle教程 。 并在Stack Overflow中搜索许多示例和说明。 规格为JSR 310 。
您可以直接与数据库交换java.time对象。 使用与JDBC 4.2或更高版本兼容的JDBC驱动程序 。 不需要字符串,不需要java.sql.*
类。
在哪里获取java.time类?
- Java SE 8 , Java SE 9 , Java SE 10和更高版本
- 内置的
- 标准Java API的一部分,具有捆绑的实现。
- Java 9添加了一些次要功能和修复。
- Java SE 6和Java SE 7
- java.time的许多功能在ThreeTen- Backport中都被反向移植到Java 6和7。
- 安卓系统
- 更高版本的Android捆绑了java.time类的实现。
- 对于早期的Android(<26), ThreeTenABP项目改编了ThreeTen-Backport (如上所述)。 请参阅如何使用ThreeTenABP… 。
ThreeTen-Extra项目使用其他类扩展了java.time。 该项目为将来可能在java.time中添加内容提供了一个试验场。 您可以在这里找到一些有用的类,比如Interval
, YearWeek
, YearQuarter
,和更多 。
#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 timeString time = df.format(Calendar.getInstance().getTime());DateFormat df1=new SimpleDateFormat("yyyy/MM/dd");//foramt dateString 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.CalendarDate 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
如何在Android中获取当前时间和日期相关推荐
- 如何在Python中获取文件创建和修改日期/时间?
我有一个脚本,该脚本需要根据文件创建和修改日期执行一些操作,但必须在Linux和Windows上运行. 在Python中获取文件创建和修改日期/时间的最佳跨平台方法是什么? #1楼 最好的功能是os. ...
- 如何在Python中获取当前时间
获取当前时间的模块/方法是什么? 获取当前时间的模块/方法是什么? 获取当前时间的模块/方法是什么? 获取当前时间的模块/方法是什么? 获取当前时间的模块/方法是什么? 获取当前时间的模块/方法是什么 ...
- android设备id完美解决方法,如何在Android中获取唯一的设备硬件ID?
您可以在下面的链接中查看此博客 [http://android-developers.blogspot.in/2011/03/identifying-app-installations.html] A ...
- audiotrack android,如何在Android中获取AudioTrack的音量?
我可以使用track.setStereoVolume(a,b);来设置audioTrack的音量. 但是我找不到像getStereoVolume()或setOnVolumeChangedHandler ...
- android获取应用权限管理,如何在android中获取应用程序权限设置?
我正在开发一个小应用程序,它只列出那些连接到互联网的应用程序.如何从Packageinfo类中读取 android清单文件以编程方式访问每个应用程序的权限设置? private void getWeb ...
- android 获取应用内存大小,如何在Android中获取当前内存使用量?
这取决于您要获得的内存查询的定义. 通常,您想知道堆内存的状态,因为如果它占用了太多内存,您就会得到OOM并使应用程序崩溃. 为此,您可以检查下一个值:final Runtime runtime = ...
- android蓝牙连接耳机分析,如何在android中获取蓝牙耳机设备的信息(特别是耳机设备名称)...
我终于解决了这个问题 . 以前我从"BluetoothAdpter"类获得了所有绑定设备的"getBondedDevices()"方法 . 但我通过使用&quo ...
- android log输出keycode,如何在android中获取keyCode
我有以下代码: tv.setOnKeyListener(new View.OnKeyListener() { public boolean onKey(View v, int keyCode, Key ...
- android自动获取系统时间,Android获取系统时间的多种方法
Android中获取系统时间有多种方法,可分为Java中Calendar类获取,java.util.date类实现,还有android中Time实现. 现总结如下: 方法一: void getTime ...
最新文章
- UVa 679 - Dropping Balls
- linux 安装 zookeeper 管理端, dubbo-admin 访问 404
- java单链表例子_写一个java链表的例子?随便举例说一下。
- HTML 5 视频/音频参考手册
- vs与git中间的阻拦--Git failed with a fatal error. error: open(“.vs/GBA/v16/Server/sqlite3/db.lock
- [转]Windows Shell 编程 第十三章 【来源:http://blog.csdn.net/wangqiulin123456/article/details/7988004】...
- CmRegisterCallback监控注册表框架
- 最常用的决策树算法(二)Random Forest、Adaboost、GBDT 算法
- 空间数据引擎oracle_GIS 与Oracle 数据库空间数据格式的转换
- python画多层网络_绘制多层n
- Python文件操作与函数目录
- PGPool使用限制
- PC管理端及评委手机打分端的浏览器兼容问题
- 应急响应-记一次“完(sang)美(xin)无(bing)缺(kuang)”的SSH口令爆破
- Unity URP贴花系统的简单使用
- 名帖46 北魏 楷书《镇北大将军元思墓志》
- JVM笔记十四:方法区
- MySQL连接查询的成本
- 用线程设计奥运倒计时100天的倒计时牌
- 传送带(三分套三分)
热门文章
- AJAX请求时status返回状态明细表 readyState的五种状态
- Caffe学习笔记2--Ubuntu 14.04 64bit 安装Caffe(GPU版本)
- Linux 性能监测:介绍
- C# 文件读取(一)
- Apache查看并发及TIME_WAIT过多的解决
- 正则表达式之全部符号解释
- 在CentOs 5.1中使用rpm安装NGINX+php+mysql(二)
- [jQuery]超出容器部分...
- Android(java)学习笔记155:中文乱码的问题处理(qq登录案例)
- POJ 2392 Space Elevator(多重背包变形)