adding hours in date time format java

后端 未结 3 2159
小鲜肉
小鲜肉 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 ) ;
    
    0 讨论(0)
  • 2021-01-06 13:06

    Convert java.util.Date into java.util.Calendar Object and use Calendar.add() method to add Hours

    SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
    Date time1 = parser.parse("7:30");
    Calendar cal =Calendar.getInstance();
    cal.setTime(time1);
    cal.add(Calendar.Hour_Of_Day, 2);
    time1 =cal.getTime();
    System.out.println(parser.format(time1));//returns 09:30
    
    0 讨论(0)
  • 2021-01-06 13:12

    java.util.Date is deprecated, you should use java.util.Calendar instead.

    SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
    Date myDate = parser.parse("7:30");
    Calendar cal =Calendar.getInstance();
    cal.setTime(myDate);
    cal.add(Calendar.HOUR_OF_DAY,2); // this will add two hours
    myDate = cal.getTime();
    

    And even better solution is to use Joda Time - Java date and time API.

    From their website - Joda-Time provides a quality replacement for the Java date and time classes.

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