如何在Java中获取当前时刻的年、月、日、小时、分钟、秒和毫秒?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2654025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?
提问by Roman
How can I get the year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java? I would like to have them as Strings
.
如何在 Java 中获取当前时刻的年、月、日、小时、分钟、秒和毫秒?我想将它们作为Strings
.
采纳答案by BalusC
You can use the getters of java.time.LocalDateTime
for that.
你可以使用的吸气剂java.time.LocalDateTime
。
LocalDateTime now = LocalDateTime.now();
int year = now.getYear();
int month = now.getMonthValue();
int day = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
int millis = now.get(ChronoField.MILLI_OF_SECOND); // Note: no direct getter available.
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Or, when you're not on Java 8 yet, make use of java.util.Calendar
.
或者,当您尚未使用 Java 8 时,请使用java.util.Calendar
.
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
Either way, this prints as of now:
无论哪种方式,这都打印为现在:
2010-04-16 15:15:17.816
To convert an int
to String
, make use of String#valueOf()
.
要将 转换int
为String
,请使用String#valueOf()
.
If your intent is after allto arrange and display them in a human friendly string format, then better use either Java8's java.time.format.DateTimeFormatter
(tutorial here),
如果您的意图毕竟是以人类友好的字符串格式排列和显示它们,那么最好使用 Java8 java.time.format.DateTimeFormatter
(此处的教程),
LocalDateTime now = LocalDateTime.now();
String format1 = now.format(DateTimeFormatter.ISO_DATE_TIME);
String format2 = now.atZone(ZoneId.of("GMT")).format(DateTimeFormatter.RFC_1123_DATE_TIME);
String format3 = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss", Locale.ENGLISH));
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
or when you're not on Java 8 yet, use java.text.SimpleDateFormat
:
或者当您尚未使用 Java 8 时,请使用java.text.SimpleDateFormat
:
Date now = new Date(); // java.util.Date, NOT java.sql.Date or java.sql.Timestamp!
String format1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(now);
String format2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH).format(now);
String format3 = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH).format(now);
System.out.println(format1);
System.out.println(format2);
System.out.println(format3);
Either way, this yields:
无论哪种方式,这都会产生:
2010-04-16T15:15:17.816 Fri, 16 Apr 2010 15:15:17 GMT 20100416151517
See also:
也可以看看:
回答by M. Jessup
Look at the API documentation for the java.util.Calendar class and its derivatives (you may be specifically interested in the GregorianCalendar class).
查看 java.util.Calendar 类及其派生类的 API 文档(您可能对 GregorianCalendar 类特别感兴趣)。
回答by crowne
Switch to joda-timeand you can do this in three lines
切换到joda-time,三行即可
DateTime jodaTime = new DateTime();
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS");
System.out.println("jodaTime = " + formatter.print(jodaTime));
You also have direct access to the individual fields of the date without using a Calendar.
您还可以直接访问日期的各个字段,而无需使用日历。
System.out.println("year = " + jodaTime.getYear());
System.out.println("month = " + jodaTime.getMonthOfYear());
System.out.println("day = " + jodaTime.getDayOfMonth());
System.out.println("hour = " + jodaTime.getHourOfDay());
System.out.println("minute = " + jodaTime.getMinuteOfHour());
System.out.println("second = " + jodaTime.getSecondOfMinute());
System.out.println("millis = " + jodaTime.getMillisOfSecond());
Output is as follows:
输出如下:
jodaTime = 2010-04-16 18:09:26.060
year = 2010
month = 4
day = 16
hour = 18
minute = 9
second = 26
millis = 60
According to http://www.joda.org/joda-time/
根据http://www.joda.org/joda-time/
Joda-Time is the de facto standard date and time library for Java. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).
Joda-Time 是 Java 的事实上的标准日期和时间库。从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310)。
回答by llappall
Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need
Calendar now = new Calendar() // 或 new GregorianCalendar(),或任何你需要的风格
now.MONTH now.HOUR
现在.MONTH 现在.HOUR
etc.
等等。
回答by pavel
Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it in production code. Joda is better.
或者使用 java.sql.Timestamp。日历有点重,我建议不要在生产代码中使用它。乔达更好。
import java.sql.Timestamp;
public class DateTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new Timestamp(System.currentTimeMillis()));
}
}
回答by Ortomala Lokni
With Java 8 and later, use the java.time package.
对于 Java 8 及更高版本,请使用java.time 包。
ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();
ZonedDateTime.now()
is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int
value.
ZonedDateTime.now()
是一种静态方法,从默认时区的系统时钟返回当前日期时间。所有 get 方法都返回一个int
值。
回答by blueberry0xff
// Java 8
System.out.println(LocalDateTime.now().getYear()); // 2015
System.out.println(LocalDateTime.now().getMonth()); // SEPTEMBER
System.out.println(LocalDateTime.now().getDayOfMonth()); // 29
System.out.println(LocalDateTime.now().getHour()); // 7
System.out.println(LocalDateTime.now().getMinute()); // 36
System.out.println(LocalDateTime.now().getSecond()); // 51
System.out.println(LocalDateTime.now().get(ChronoField.MILLI_OF_SECOND)); // 100
// Calendar
System.out.println(Calendar.getInstance().get(Calendar.YEAR)); // 2015
System.out.println(Calendar.getInstance().get(Calendar.MONTH ) + 1); // 9
System.out.println(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)); // 29
System.out.println(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)); // 7
System.out.println(Calendar.getInstance().get(Calendar.MINUTE)); // 35
System.out.println(Calendar.getInstance().get(Calendar.SECOND)); // 32
System.out.println(Calendar.getInstance().get(Calendar.MILLISECOND)); // 481
// Joda Time
System.out.println(new DateTime().getYear()); // 2015
System.out.println(new DateTime().getMonthOfYear()); // 9
System.out.println(new DateTime().getDayOfMonth()); // 29
System.out.println(new DateTime().getHourOfDay()); // 7
System.out.println(new DateTime().getMinuteOfHour()); // 19
System.out.println(new DateTime().getSecondOfMinute()); // 16
System.out.println(new DateTime().getMillisOfSecond()); // 174
// Formatted
// 2015-09-28 17:50:25.756
System.out.println(new Timestamp(System.currentTimeMillis()));
// 2015-09-28T17:50:25.772
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.ENGLISH).format(new Date()));
// Java 8
// 2015-09-28T17:50:25.810
System.out.println(LocalDateTime.now());
// joda time
// 2015-09-28 17:50:25.839
System.out.println(DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS").print(new org.joda.time.DateTime()));
回答by Lucke
in java 7 Calendar one line
在 java 7 Calendar 一行
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(Calendar.getInstance().getTime())
回答by Basil Bourque
tl;dr
tl;博士
ZonedDateTime.now( // Capture current moment as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "America/Montreal" ) // Specify desired/expected time zone. Or pass `ZoneId.systemDefault` for the JVM's current default time zone.
) // Returns a `ZonedDateTime` object.
.getMinute() // Extract the minute of the hour of the time-of-day from the `ZonedDateTime` object.
42
42
ZonedDateTime
ZonedDateTime
To capture the current moment as seen in the wall-clock time used by the people of a particular region (a time zone), use ZonedDateTime
.
要捕获特定地区(时区)的人们使用的挂钟时间中看到的当前时刻,请使用ZonedDateTime
.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.
时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any momentduring runtime(!), so your results may vary. Better to specify your desired/expected time zoneexplicitly as an argument.
如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能会在运行时随时更改(!),因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。
Specify a proper time zone namein the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are nottrue time zones, not standardized, and not even unique(!).
以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/region
America/Montreal
Africa/Casablanca
Pacific/Auckland
EST
IST
ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Call any of the many getters to pull out pieces of the date-time.
调用许多 getter 中的任何一个来提取日期时间的片段。
int year = zdt.getYear() ;
int monthNumber = zdt.getMonthValue() ;
String monthName = zdt.getMonth().getDisplayName( TextStyle.FULL , Locale.JAPAN ) ; // Locale determines human language and cultural norms used in localizing. Note that `Locale` has *nothing* to do with time zone.
int dayOfMonth = zdt.getDayOfMonth() ;
String dayOfWeek = zdt.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
int hour = zdt.getHour() ; // Extract the hour from the time-of-day.
int minute = zdt.getMinute() ;
int second = zdt.getSecond() ;
int nano = zdt.getNano() ;
The java.timeclasses resolve to nanoseconds. Your Question asked for the fraction of a second in milliseconds. Obviously, you can divide by a million to truncate nanoseconds to milliseconds, at the cost of possible data loss. Or use the TimeUnit
enum for such conversion.
该java.time类解析为纳秒。您的问题要求以毫秒为单位的几分之一秒。显然,您可以除以一百万以将纳秒截断为毫秒,但代价是可能会丢失数据。或者使用TimeUnit
枚举进行此类转换。
long millis = TimeUnit.NANOSECONDS.toMillis( zdt.getNano() ) ;
DateTimeFormatter
DateTimeFormatter
To produce a String
to combine pieces of text, use DateTimeFormatter
class. Search Stack Overflow for more info on this.
要生成一个String
组合文本片段,请使用DateTimeFormatter
类。搜索 Stack Overflow 以获取更多信息。
Instant
Instant
Usually best to track moments in UTC. To adjust from a zoned date-time to UTC, extract a Instant
.
通常最好以 UTC 时间跟踪时刻。要将分区日期时间调整为 UTC,请提取Instant
.
Instant instant = zdt.toInstant() ;
And go back again.
然后再回去。
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDateTime
LocalDateTime
A couple of other Answers use the LocalDateTime
class. That class in not appropriate to the purpose of tracking actual moments, specific moments on the timeline, as it intentionally lacks any concept of time zone or offset-from-UTC.
其他几个答案使用LocalDateTime
该类。该类不适合跟踪实际时刻,时间线上的特定时刻,因为它故意缺少任何时区或UTC偏移量的概念。
So what is LocalDateTime
good for? Use LocalDateTime
when you intend to apply a date & time to any localityor all localities, rather than one specific locality.
那么有什么LocalDateTime
好处呢?使用LocalDateTime
时,你打算日期和时间适用于任何地方或各地方,而不是一个特定的地方。
For example, Christmas this year starts at the LocalDateTime.parse( "2018-12-25T00:00:00" )
. That value has no meaning until you apply a time zone (a ZoneId
) to get a ZonedDateTime
. Christmas happens first in Kiribati, then later in New Zealand and far east Asia. Hours later Christmas starts in India. More hour later in Africa & Europe. And still not Xmas in the Americas until several hours later. Christmas starting in any oneplace should be represented with ZonedDateTime
. Christmas everywhereis represented with a LocalDateTime
.
例如,今年的圣诞节从LocalDateTime.parse( "2018-12-25T00:00:00" )
. 在您应用时区 (a ZoneId
) 来获取ZonedDateTime
. 圣诞节首先发生在基里巴斯,然后是新西兰和远东地区。几个小时后,圣诞节在印度开始。一小时后在非洲和欧洲。直到几个小时后,美洲仍然没有圣诞节。在任何一个地方开始的圣诞节都应该用 表示ZonedDateTime
。圣诞节到处都用LocalDateTime
.
About java.time
关于java.time
The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
该java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date
, Calendar
, & SimpleDateFormat
。
The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.
现在处于维护模式的Joda-Time项目建议迁移到java.time类。
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310。
You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*
classes.
您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*
Where to obtain the java.time classes?
从哪里获得 java.time 类?
- Java SE 8, Java SE 9, Java SE 10, and later
- Built-in.
- Part of the standard Java API with a bundled implementation.
- Java 9 adds some minor features and fixes.
- Java SE 6and Java SE 7
- Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
- Android
- Later versions of Android bundle implementations of the java.time classes.
- For earlier Android (<26), the ThreeTenABPproject adapts ThreeTen-Backport(mentioned above). See How to use ThreeTenABP….
- Java SE 8、Java SE 9、Java SE 10及更高版本
- 内置。
- 具有捆绑实现的标准 Java API 的一部分。
- Java 9 添加了一些小功能和修复。
- Java SE 6和Java SE 7
- 多的java.time功能后移植到Java 6和7在ThreeTen-反向移植。
- 安卓
- 更高版本的 Android 捆绑实现 java.time 类。
- 对于早期的 Android(<26),ThreeTenABP项目采用了ThreeTen-Backport(上面提到过)。请参阅如何使用ThreeTenABP ...。