在日期时间格式java中添加小时
SimpleDateFormat parser = new SimpleDateFormat("HH:mm"); Date time1 = parser.parse("7:30");
现在,如果我想再增加2个小时到time1
,例如:
7:30 + 2 = 9:30
我该如何加2小时?
不推荐使用java.util.Calendar
,您应该使用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日期和时间API 。
从他们的网站–Joda-Time为Java日期和时间类提供了高质量的替代品。
将java.util.Date
转换为java.util.Calendar
对象,并使用Calendar.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
TL;博士
LocalTime.parse( "07:30" ).plusHours( 2 )
…要么…
ZonedDateTime.now( ZoneId.of( " Pacific/Auckland" ) ) .plusHours( 2 )
java.time
应该避免旧的日期时间类,例如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为单位捕获UTC中的当前时刻。
Instant instant = Instant.now();
加秒两小时。 TimeUnit
类可以将小时转换为秒。
long seconds = TimeUnit.HOURS.toSeconds( 2 ); Instant instantLater = instant.plusSeconds( seconds );
ZonedDateTime
要查看某个社区的挂钟时间,请应用时区。 应用ZoneId
以获取ZonedDateTime
对象。
ZoneId z = ZoneId.of( "America/Montreal" ); ZonedDateTime zdt = instant.atZone( z );
你可以增加几个小时。 ZonedDateTime
类处理夏令时等exception。
ZonedDateTime zdtLater = zdt.plusHours( 2 );
Duration
您可以将这两个小时表示为对象。
Duration d = Duration.ofHours( 2 ) ; ZonedDateTime zdtLater = zdt.plus( d ) ;