Date object to Calendar [Java]

后端 未结 7 1913
花落未央
花落未央 2020-12-02 19:31

I have a class Movie in it i have a start Date, a duration and a stop Date. Start and stop Date are Date Objects (private Date startDate ...) (It\'s an assignment so i cant

相关标签:
7条回答
  • 2020-12-02 20:06

    Calendar.setTime()

    It's often useful to look at the signature and description of API methods, not just their name :) - Even in the Java standard API, names can sometimes be misleading.

    0 讨论(0)
  • 2020-12-02 20:10

    What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time:

    Date date;
    Calendar myCal = new GregorianCalendar();
    myCal.setTime(date);
    

    However, another approach is to not use Date at all. You could use an approach like this:

    private Calendar startTime;
    private long duration;
    private long startNanos;   //Nano-second precision, could be less precise
    ...
    this.startTime = Calendar.getInstance();
    this.duration = 0;
    this.startNanos = System.nanoTime();
    
    public void setEndTime() {
            this.duration = System.nanoTime() - this.startNanos;
    }
    
    public Calendar getStartTime() {
            return this.startTime;
    }
    
    public long getDuration() {
            return this.duration;
    }
    

    In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.

    0 讨论(0)
  • 2020-12-02 20:15

    tl;dr

    Instant stop = 
        myUtilDateStart.toInstant()
                       .plus( Duration.ofMinutes( x ) ) 
    ;
    

    java.time

    Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.

    The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.

    If your Calendar is actually a GregorianCalendar you can convert to a ZonedDateTime. Find new methods added to the old classes to facilitate conversion to/from java.time types.

    if( myUtilCalendar instanceof GregorianCalendar ) {
        GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
        ZonedDateTime zdt = gregCal.toZonedDateTime();  // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
    end if 
    

    If your Calendar is not a Gregorian, call toInstant to get an Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

    Instant instant = myCal.toInstant();
    

    Similarly, if starting with a java.util.Date object, convert to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

    Instant instant = myUtilDate.toInstant();
    

    Apply a time zone to get a ZonedDateTime.

    ZoneId z = ZoneId.of( "America/Montreal" );
    ZonedDateTime zdt = instant.atZone( z );
    

    To get a java.util.Date object, go through the Instant.

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

    For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answer to another Question.

    Duration

    Represent the span of time as a Duration object. Your input for the duration is a number of minutes as mentioned in the Question.

    Duration d = Duration.ofMinutes( yourMinutesGoHere );
    

    You can add that to the start to determine the stop.

    Instant stop = startInstant.plus( d ); 
    

    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.

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

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

    Where to obtain the java.time classes?

    • Java SE 8 and SE 9 and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use….

    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.

    0 讨论(0)
  • 2020-12-02 20:17

    You don't need to convert to Calendar for this, you can just use getTime()/setTime() instead.

    getTime(): Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

    setTime(long time) : Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. )

    There are 1000 milliseconds in a second, and 60 seconds in a minute. Just do the math.

        Date now = new Date();
        Date oneMinuteInFuture = new Date(now.getTime() + 1000L * 60);
        System.out.println(now);
        System.out.println(oneMinuteInFuture);
    

    The L suffix in 1000 signifies that it's a long literal; these calculations usually overflows int easily.

    0 讨论(0)
  • 2020-12-02 20:22

    something like

    movie.setStopDate(movie.getStartDate() + movie.getDurationInMinutes()* 60000);
    
    0 讨论(0)
  • 2020-12-02 20:23
    Calendar tCalendar = Calendar.getInstance();
    tCalendar.setTime(date);
    

    date is a java.util.Date object. You may use Calendar.getInstance() as well to obtain the Calendar instance(much more efficient).

    0 讨论(0)
提交回复
热议问题