我有一个名为时间的字符串变量2016-11-30T00:06:42+05:30
持续时间32700,即545分钟。
我想将持续时间添加到上面的字符串时间戳中,并且需要计算开始时间和结束时间。
所以我想获取 StartTime:00:06 和 EndTime:09:05。
我试过了,但没用
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = sdf.parse(startTime.toString());
Timestamp ts_now = new Timestamp(date.getTime());
System.out.println(">>>>>>"+date);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(ts_now.getTime());
cal.add(Calendar.SECOND, Integer.parseInt(Value.toString()));
Timestamp later = new Timestamp(cal.getTime().getTime());
System.out.println(">>>>>>"+later);
我尝试使用 X ,Z 但出现错误,例如
Exception in thread "main" java.text.ParseException: Unparseable date: "2016-11-30T00:06:42+05:30"
at java.text.DateFormat.parse(DateFormat.java:366)
at oneraise.radis.thread.mavenproject1.ParseJson.main(ParseJson.java:48)
我是java新手,谁能帮助我
谢谢
最佳答案
tl;博士
OffsetDateTime.parse( "2016-11-30T00:06:42+05:30" )
.plus( Duration.ofSeconds( 32_700L ) )
详细信息
避免使用麻烦且令人困惑的日期时间类,例如 java.util.Date
和 Calendar
,它们现在是遗留的,已被 java.time 类取代。
您的输入字符串符合标准ISO 8601格式。此类字符串可以直接由 java.time 类解析,无需指定格式模式。
解析为OffsetDateTime
对象。
OffsetDateTime odt = OffsetDateTime.parse( "2016-11-30T00:06:42+05:30" );
另一个答案中使用的 ZonedDateTime
类在这里不合适。此输入字符串仅包含 offset-from-UTC ,不是完整的时区,例如 Asia/Kolkata
。所以 OffsetDateTime
是这里使用的类。
Duration
类处理你的时间跨度,即秒数。
Duration d = Duration.ofSeconds( 32_700L );
添加到您的日期时间对象。
OffsetDateTime odtLater = odt.plus( d );
提示:要查看 UTC 中的 OffsetDateTime
值,提取一个Instant
。
Instant instant = odt.toInstant();
数据库
对于数据库访问,您的 JDBC 4.2 兼容驱动程序可能能够通过 get/setObject 方法使用 java.time 对象。
如果是这样,则无需使用旧的 java.sql.Timestamp
类或其同级类。
myPreparedStatement.setObject( … , odt );
如果没有,请使用添加到旧 date-lime 类中的新转换方法。
java.sql.Timestamp ts = java.sql.Timestamp.from( odt.toInstant() );
关于java - 如何将秒添加到字符串时间戳(yyyy-mm-ddTH :i:s+tz) in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40931498/