How to initialize a variable of date type in java?

前端 未结 5 1667
借酒劲吻你
借酒劲吻你 2021-02-20 02:57
import java.util.Date;
Date firstDate; 

I don\'t know how to intialize the firstDate for example for String you say

String line1=\"Fir         


        
5条回答
  •  执笔经年
    2021-02-20 03:43

    tl;dr

    Use Instant, replacement for java.util.Date.

    Instant.now()  // Capture current moment as seen in UTC.
    

    If you must have a Date, convert.

    java.util.Date.from( Instant.now() ) 
    

    java.time

    The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendous improvement, inspired by the successful Joda-Time library.

    The java.time classes tend to use static factory methods rather than constructors for instantiating objects.

    To get the current moment in UTC time zone:

    Instant instant = Instant.now();
    

    To get the current moment in a particular time zone:

    ZoneId zoneId = ZoneId.of( "America/Montreal" );
    ZonedDateTime zdt = ZonedDateTime.now( zoneId );
    

    If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant.

    java.util.Date date = java.util.Date.from( zdt.toInstant() );
    


    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.

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

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

    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.

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Most 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 ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

提交回复
热议问题