简体   繁体   English

如何在Java中获取当前时刻的年、月、日、小时、分钟、秒和毫秒?

[英]How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

How can I get the year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?如何在 Java 中获取当前时刻的年、月、日、小时、分钟、秒和毫秒? I would like to have them as Strings .我想将它们作为Strings

You can use the getters of java.time.LocalDateTime for that.您可以java.time.LocalDateTime使用java.time.LocalDateTime的 getter。

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 all to 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:也可以看看:

Switch to joda-time and 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. Joda-Time 是 Java 的事实上的标准日期和时间库。 From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310)。

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

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. ZonedDateTime.now()是一个静态方法,从默认时区的系统时钟返回当前日期时间。 All the get methods return an int value.所有 get 方法都返回一个int值。

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

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 France is 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.如果未指定时区,JVM 会隐式应用其当前默认时区。 That default may change at any moment during runtime(!), so your results may vary.该默认值可能会在运行时随时更改(!),因此您的结果可能会有所不同。 Better to specify your desired/expected time zone explicitly as an argument.最好将您想要/预期的时区明确指定为参数。

Specify a proper time zone name in the format of continent/region , such as America/Montreal , Africa/Casablanca , or Pacific/Auckland .continent/region的格式指定正确的时区名称,例如America/MontrealAfrica/CasablancaPacific/Auckland Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).永远不要使用ESTIST等 3-4 个字母的缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

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.time classes resolve to nanoseconds .java.time类解析为纳秒 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.或者使用TimeUnit枚举进行此类转换。

long millis = TimeUnit.NANOSECONDS.toMillis( zdt.getNano() ) ;

DateTimeFormatter

To produce a String to combine pieces of text, use DateTimeFormatter class.要生成一个String来组合文本片段,请使用DateTimeFormatter类。 Search Stack Overflow for more info on this.搜索 Stack Overflow 以获取更多信息。

Instant

Usually best to track moments in UTC.通常最好以 UTC 时间跟踪时刻。 To adjust from a zoned date-time to UTC, extract a Instant .要将分区日期时间调整为 UTC,请提取Instant

Instant instant = zdt.toInstant() ;

And go back again.然后再回去。

ZonedDateTime zdt = instant.atZone( ZoneId.of( "Africa/Tunis" ) ) ;

LocalDateTime

A couple of other Answers use the LocalDateTime class.其他几个答案使用LocalDateTime类。 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.该类不适合跟踪实际时刻,时间线上的特定时刻,因为它故意缺少任何时区或UTC偏移量的概念。

So what is LocalDateTime good for?那么LocalDateTime什么用呢? Use LocalDateTime when you intend to apply a date & time to any locality or all localities , rather than one specific locality.当您打算将日期和时间应用于任何地点所有地点而不是一个特定地点时,请使用LocalDateTime

For example, Christmas this year starts at the LocalDateTime.parse( "2018-12-25T00:00:00" ) .例如,今年的圣诞节从LocalDateTime.parse( "2018-12-25T00:00:00" ) That value has no meaning until you apply a time zone (a ZoneId ) to get a ZonedDateTime .在您应用时区( ZoneId )来获取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 one place should be represented with ZonedDateTime .圣诞节在任何一个地方出发应该表示ZonedDateTime Christmas everywhere is represented with a LocalDateTime .圣诞节到处都用LocalDateTime表示。


About java.time关于java.time

The java.time framework is built into Java 8 and later. java.time框架内置于 Java 8 及更高版本中。 These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .这些类取代麻烦的老传统日期时间类,如java.util.DateCalendar ,和SimpleDateFormat

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial .要了解更多信息,请参阅Oracle 教程 And search Stack Overflow for many examples and explanations.并在 Stack Overflow 上搜索许多示例和解释。 Specification is JSR 310 .规范是JSR 310

You may exchange java.time objects directly with your database.您可以直接与您的数据库交换java.time对象。 Use a JDBC driver compliant with JDBC 4.2 or later.使用符合JDBC 4.2或更高版本的JDBC 驱动程序 No need for strings, no need for java.sql.* classes.不需要字符串,不需要java.sql.*类。

Where to obtain the java.time classes?从哪里获得 java.time 类?

Or use java.sql.Timestamp.或者使用 java.sql.Timestamp。 Calendar is kinda heavy,I would recommend against using it in production code.日历有点重,我建议不要在生产代码中使用它。 Joda is better.乔达更好。

import java.sql.Timestamp;

public class DateTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new Timestamp(System.currentTimeMillis()));
    }
}

在 java 7 Calendar 一行

new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(Calendar.getInstance().getTime())

使用格式模式 'dd-MM-yyyy HH:mm:ss aa' 获取日期为21-10-2020 20:53:42 pm

查看 java.util.Calendar 类及其派生类的 API 文档(您可能对 GregorianCalendar 类特别感兴趣)。

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.等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java日历获取当前日期,没有小时,分钟,秒和毫秒,以毫秒为单位 - Java calendar get the current date, without hours, minutes, seconds and milliseconds, in milliseconds Android:将秒转换为年,日,小时,分钟,秒 - Android : Convert seconds to year, day, hours, minutes, seconds Java-毫秒到月/年(不仅是当前时间) - Java - Milliseconds to Month/Year (not just the current time) 将 UTC 时间转换为本地时间,同时使用本地年/月/日并指定小时/分钟 JAVA - Convert UTC time to local time while using the local year/month/day and specifying the hours/minutes JAVA 在Java中以毫秒为单位获取当前日期 - Get Current Day in Milliseconds In Java 如何从Java JSpinner仅获取年,月,日,荷尔和秒 - How to get only year, month,day,horus and seconds from Java JSpinner Java / Android:原生API,可转换以毫秒为单位的小时,分​​钟和秒 - Java/Android: Native API to transform hours, minutes and seconds in milliseconds 使用Java的转换器从数秒到数天,数小时,数分钟和数秒的问题 - Problems with a converter from seconds to day, hours, minutes, and seconds using Java 如何显示时间,例如小时:分钟:秒:毫秒:微秒? - How to display time like hours:minutes:seconds:milliseconds:microseconds? Java将秒转换为年日小时秒 - Java converting seconds to year day hours minute seconds
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM