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

时间:2023-01-31 20:23:52

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中获得当前时刻的年、月、日、小时、分钟、秒和毫秒?我希望它们是字符串。

9 个解决方案

#1


214  

You can use the getters of java.time.LocalDateTime for that.

您可以使用java.time的getter。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#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:

#2


29  

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. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).

Joda-Time是Java事实上的标准日期和时间库。从Java SE 8开始,用户被要求迁移到Java。时间(jsr - 310)。

#3


4  

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

#4


4  

With Java 8 and later, use the java.time package.

使用Java 8或更高版本,请使用Java。包的时间。

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值。

#5


1  

Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it in production code. Joda is better.

或使用java.sql.Timestamp。日历有点重,我建议不要在生产代码中使用它。Joda更好。

import java.sql.Timestamp;

public class DateTest {

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

#6


1  

tl;dr

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

如果没有指定时区,JVM将隐式地应用其当前默认时区。在运行时(!)中,该默认值随时可能改变,因此您的结果可能会有所不同。最好将所需的/预期的时区明确指定为参数。

Specify a proper time zone name in 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 not true time zones, not standardized, and not even unique(!).

以大洲/地区的格式指定适当的时区名称,例如:America/Montreal, Africa/Casablanca, Pacific/Auckland。千万不要使用像EST或IST这样的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. 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。时间类解析为纳秒。你的问题只需要几毫秒。显然,您可以除以100万,以将纳秒截断为毫秒,以可能的数据损失为代价。或者使用TimeUnit enum进行此类转换。

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

DateTimeFormatter

To produce a String to combine pieces of text, use DateTimeFormatter class. Search Stack Overflow for more info on this.

要生成一个字符串来组合文本片段,请使用DateTimeFormatter类。搜索堆栈溢出来获取更多信息。

Instant

Usually best to track moments in UTC. To adjust from a zoned date-time to UTC, extract a Instant.

通常最好跟踪UTC的时刻。要从分区日期-时间调整到UTC,请提取片刻。

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. 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 locality or all localities, rather than one specific locality.

那么LocalDateTime有什么用呢?使用LocalDateTime,当您打算将日期和时间应用于任何地点或所有地方,而不是一个特定的地点。

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

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 one place should be represented with ZonedDateTime. Christmas everywhere is represented with a LocalDateTime.

例如,今年的圣诞节从LocalDateTime开始。解析(“2018 - 12 - 25 t00:00:00”)。这个值没有任何意义,除非您应用一个时区(一个ZoneId)来获得一个ZonedDateTime。圣诞节首先在基里巴斯,然后在新西兰和远东地区。几个小时后,圣诞节在印度开始。一小时后在非洲和欧洲。直到几个小时后,美洲才迎来了圣诞节。从任何一个地方开始的圣诞节应该用ZonedDateTime来表示。无处不在的圣诞节用LocalDateTime表示。


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java。时间框架构建在Java 8和之后。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

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

Where to obtain the java.time classes?

在哪里获得java。时间类?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • 内置的。
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9 adds some minor features and fixes.
    • Java 9添加了一些次要的特性和修复。
  • Java SE 8, Java SE 9, Java SE 10,以及后来的内置。带有捆绑实现的标准Java API的一部分。Java 9添加了一些次要的特性和修复。
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 大部分java。时间功能在三个回端移植到Java 6和7。
  • Java SE 6和Java SE 7大部分的Java。时间功能在三个回端移植到Java 6和7。
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • java的Android bundle实现的后续版本。时间类。
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android (<26), ThreeTenABP项目适应了ThreeTen-Backport(上面提到的)。看到如何使用ThreeTenABP ....
  • Android后期版本的java捆绑包实现。时间类。对于早期的Android (<26), ThreeTenABP项目适应了ThreeTen-Backport(上面提到的)。看到如何使用ThreeTenABP ....

#7


0  

in java 7 Calendar one line

在java 7日历中,一行

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

#8


-2  

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的API文档。Calendar类及其派生类(您可能对GregorianCalendar类特别感兴趣)。

#9


-2  

Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need

Calendar now = new Calendar() //或新的GregorianCalendar(),或您需要的任何风味

now.MONTH now.HOUR

现在。月now.HOUR

etc.

等。

#1


214  

You can use the getters of java.time.LocalDateTime for that.

您可以使用java.time的getter。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#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:

#2


29  

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. From Java SE 8 onwards, users are asked to migrate to java.time (JSR-310).

Joda-Time是Java事实上的标准日期和时间库。从Java SE 8开始,用户被要求迁移到Java。时间(jsr - 310)。

#3


4  

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

#4


4  

With Java 8 and later, use the java.time package.

使用Java 8或更高版本,请使用Java。包的时间。

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值。

#5


1  

Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it in production code. Joda is better.

或使用java.sql.Timestamp。日历有点重,我建议不要在生产代码中使用它。Joda更好。

import java.sql.Timestamp;

public class DateTest {

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

#6


1  

tl;dr

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

如果没有指定时区,JVM将隐式地应用其当前默认时区。在运行时(!)中,该默认值随时可能改变,因此您的结果可能会有所不同。最好将所需的/预期的时区明确指定为参数。

Specify a proper time zone name in 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 not true time zones, not standardized, and not even unique(!).

以大洲/地区的格式指定适当的时区名称,例如:America/Montreal, Africa/Casablanca, Pacific/Auckland。千万不要使用像EST或IST这样的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. 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。时间类解析为纳秒。你的问题只需要几毫秒。显然,您可以除以100万,以将纳秒截断为毫秒,以可能的数据损失为代价。或者使用TimeUnit enum进行此类转换。

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

DateTimeFormatter

To produce a String to combine pieces of text, use DateTimeFormatter class. Search Stack Overflow for more info on this.

要生成一个字符串来组合文本片段,请使用DateTimeFormatter类。搜索堆栈溢出来获取更多信息。

Instant

Usually best to track moments in UTC. To adjust from a zoned date-time to UTC, extract a Instant.

通常最好跟踪UTC的时刻。要从分区日期-时间调整到UTC,请提取片刻。

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. 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 locality or all localities, rather than one specific locality.

那么LocalDateTime有什么用呢?使用LocalDateTime,当您打算将日期和时间应用于任何地点或所有地方,而不是一个特定的地点。

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

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 one place should be represented with ZonedDateTime. Christmas everywhere is represented with a LocalDateTime.

例如,今年的圣诞节从LocalDateTime开始。解析(“2018 - 12 - 25 t00:00:00”)。这个值没有任何意义,除非您应用一个时区(一个ZoneId)来获得一个ZonedDateTime。圣诞节首先在基里巴斯,然后在新西兰和远东地区。几个小时后,圣诞节在印度开始。一小时后在非洲和欧洲。直到几个小时后,美洲才迎来了圣诞节。从任何一个地方开始的圣诞节应该用ZonedDateTime来表示。无处不在的圣诞节用LocalDateTime表示。


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java。时间框架构建在Java 8和之后。这些类取代了麻烦的旧遗留日期时间类(如java.util)。日期,日历,& SimpleDateFormat。

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

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

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多,请参阅Oracle教程。和搜索堆栈溢出为许多例子和解释。规范是JSR 310。

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

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

Where to obtain the java.time classes?

在哪里获得java。时间类?

  • Java SE 8, Java SE 9, Java SE 10, and later
    • Built-in.
    • 内置的。
    • Part of the standard Java API with a bundled implementation.
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9 adds some minor features and fixes.
    • Java 9添加了一些次要的特性和修复。
  • Java SE 8, Java SE 9, Java SE 10,以及后来的内置。带有捆绑实现的标准Java API的一部分。Java 9添加了一些次要的特性和修复。
  • Java SE 6 and Java SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • 大部分java。时间功能在三个回端移植到Java 6和7。
  • Java SE 6和Java SE 7大部分的Java。时间功能在三个回端移植到Java 6和7。
  • Android
    • Later versions of Android bundle implementations of the java.time classes.
    • java的Android bundle实现的后续版本。时间类。
    • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
    • 对于早期的Android (<26), ThreeTenABP项目适应了ThreeTen-Backport(上面提到的)。看到如何使用ThreeTenABP ....
  • Android后期版本的java捆绑包实现。时间类。对于早期的Android (<26), ThreeTenABP项目适应了ThreeTen-Backport(上面提到的)。看到如何使用ThreeTenABP ....

#7


0  

in java 7 Calendar one line

在java 7日历中,一行

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

#8


-2  

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的API文档。Calendar类及其派生类(您可能对GregorianCalendar类特别感兴趣)。

#9


-2  

Calendar now = new Calendar() // or new GregorianCalendar(), or whatever flavor you need

Calendar now = new Calendar() //或新的GregorianCalendar(),或您需要的任何风味

now.MONTH now.HOUR

现在。月now.HOUR

etc.

等。