SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date time1 = parser.parse("7:30");
Now if I want to add 2 more hours to time1
, like:
7:30 + 2 = 9:30
how do I add the 2 hours?
SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date time1 = parser.parse("7:30");
Now if I want to add 2 more hours to time1
, like:
7:30 + 2 = 9:30
how do I add the 2 hours?
java.util.Date
は推奨されないため、代わりに使用する必要がありますjava.util.Calendar
。
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();
さらに良い解決策は、Joda Time - Java date and time APIを使用することです。
Web サイトから - Joda-Time は、Java の日付と時刻のクラスの高品質な代替品を提供します。
オブジェクトに変換java.util.Date
し、 Calendar.add()メソッドを使用して時間を追加しますjava.util.Calendar
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
LocalTime.parse( "07:30" ).plusHours( 2 )
…または…</p>
ZonedDateTime.now( ZoneId.of( " Pacific/Auckland" ) )
.plusHours( 2 )
java.util.Date、.Calendar、および java.text.SimpleDateFormat などの古い日時クラスは避ける必要があり、現在は java.time クラスに取って代わられています。
LocalTime
時刻のみの値の場合は、LocalTime
クラスを使用します。
LocalTime lt = LocalTime.parse( "07:30" );
LocalTime ltLater = lt.plusHours( 2 );
String output = ltLater.toString(); // 09:30
Instant
特定の についてjava.util.Date
、古いクラスに追加された新しいメソッドを使用して java.time に変換します。このInstant
クラスは、ナノ秒単位の精度で UTC のタイムライン上の瞬間を表します。
Instant instant = myUtilDate.toInstant();
または、現在の瞬間を UTC としてキャプチャしInstant
ます。
Instant instant = Instant.now();
2 時間を秒として追加します。TimeUnit
クラスは時間を秒に変換できます。
long seconds = TimeUnit.HOURS.toSeconds( 2 );
Instant instantLater = instant.plusSeconds( seconds );
ZonedDateTime
一部のコミュニティの実時間で表示するには、タイム ゾーンを適用します。a を適用しZoneId
てオブジェクトを取得しZonedDateTime
ます。
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
時間を追加できます。このZonedDateTime
クラスは、夏時間などの異常を処理します。
ZonedDateTime zdtLater = zdt.plusHours( 2 );
Duration
その 2 時間をオブジェクトとして表すことができます。
Duration d = Duration.ofHours( 2 ) ;
ZonedDateTime zdtLater = zdt.plus( d ) ;