adding hours in date time format java

后端 未结 3 2181
小鲜肉
小鲜肉 2021-01-06 12:48
SimpleDateFormat parser = new SimpleDateFormat(\"HH:mm\");
Date time1 = parser.parse(\"7:30\");

Now if I want to add 2 more hours to time1

3条回答
  •  轮回少年
    2021-01-06 12:56

    tl;dr

    LocalTime.parse( "07:30" ).plusHours( 2 )
    

    …or…

    ZonedDateTime.now( ZoneId.of( " Pacific/Auckland" ) )
        .plusHours( 2 )
    

    java.time

    The old date-time classes such as java.util.Date, .Calendar, and java.text.SimpleDateFormat should be avoided, now supplanted by the java.time classes.

    LocalTime

    For a time-of-day only value, use the LocalTime class.

    LocalTime lt = LocalTime.parse( "07:30" );
    LocalTime ltLater = lt.plusHours( 2 );  
    String output = ltLater.toString();  // 09:30
    

    Instant

    For a given java.util.Date, convert to java.time using new methods added to the old classes. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.

    Instant instant = myUtilDate.toInstant();
    

    Or capture current moment in UTC as an Instant.

    Instant instant = Instant.now();
    

    Add two hours as seconds. The TimeUnit class can convert hours to seconds.

    long seconds = TimeUnit.HOURS.toSeconds( 2 );
    Instant instantLater = instant.plusSeconds( seconds );
    

    ZonedDateTime

    To view in the wall-clock time of some community, apply a time zone. Apply a ZoneId to get a ZonedDateTime object.

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

    You can add hours. The ZonedDateTime class handles anomalies such as Daylight Saving Time.

    ZonedDateTime zdtLater = zdt.plusHours( 2 );
    

    Duration

    You can represent that two hours as an object.

    Duration d = Duration.ofHours( 2 ) ;
    ZonedDateTime zdtLater = zdt.plus( d ) ;
    

提交回复
热议问题