我正在使用java.text.DateFormat来显示应用程序用户的日期和时间。下面是我测试输出的代码。
问题是日期显示为1970年(参见下面的输出)。如何将其更新为当前日期和时间。
当前输出:
1 Jan 1970 01:00:00
当前代码:
DateFormat[] formats = new DateFormat[] {
DateFormat.getDateTimeInstance(),
};
for (DateFormat df : formats) {
Log.d("Dateformat", "Date format: " + (df.format(new Date(0))));
}
如果上述情况不可行,我可以使用以下方法获取当前时间和日期:
Time now = new Time();
now.setToNow();
String date= now.toString();
输出:
20140722T133458Europe/London(2,202,3600,1,1406032498)
如何调整此项以使其对用户可读?
答案 0 :(得分:3)
只需在第一个代码段中写下new Date()
而不是new Date(0)
。当您编写new Date(some number)
时,它会生成一个日期,即1/1/1970 00:00:00Z
答案 1 :(得分:0)
使用此 -
String S = new SimpleDateFormat("MM/dd/yyyy").format(System.currentTimeMillis());
答案 2 :(得分:0)
Instant.now()
.atZone( ZoneId.of( "America/Montreal" ) )
.format( DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH )
)
Instant
接受的Answer by Wallace是正确的。
但是要知道你正在使用现在由java.time类取代的麻烦的旧日期时间类。
Instant
类代表UTC中时间轴上的一个时刻,分辨率为nanoseconds(小数部分最多九(9)位)。
Instant instant = Instant.now(); // Current moment in UTC.
要根据ISO 8601标准生成表示该时刻格式的字符串,只需致电toString
。
ZonedDateTime
要通过某个地区wall-clock time的镜头查看同一时刻,请应用ZoneId
获取ZonedDateTime
。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z ); // Adjust from UTC to a specific time zone. Same moment, different wall-clock time.
DateTimeFormatter
为了向用户演示,让java.time使用DateTimeFormatter
类自动进行本地化。
要进行本地化,请指定:
FormatStyle
确定字符串的长度或缩写。Locale
确定(a)翻译日期名称,月份名称等的人类语言,以及(b)决定缩写,大小写,标点符号等问题的文化规范。< / LI>
示例:
Locale l = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( l );
String output = zdt.format( f );
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,.Calendar
和&amp; java.text.SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如Interval
,YearWeek
,YearQuarter
和more。