-5

I am facing issue like I have a datasheet which have a string value like 123459 which is a time and I have another column where I am adding in value as plus 5 seconds. When I am adding value its add as 123464 instead of 123504. Could anyone help me to resolve this?

Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
  • Possible duplicate of [Parse clock time in java 8](https://stackoverflow.com/questions/39870160/parse-clock-time-in-java-8). Or of [How to format a double value as time](https://stackoverflow.com/questions/49092348/how-to-format-a-double-value-as-time). – Ole V.V. Mar 13 '18 at 05:34
  • I did not downvote. In case you were wondering about the downvotes and the votes to close, I suspect they are because you don’t show any search and research effort nor any attempt to solve your problem yourself. You’re supposed to do that. And it generally gives us a better starting point for helping you, so it’ll be to your own advantage. – Ole V.V. Mar 13 '18 at 05:37

2 Answers2

2

Use the java.time classes built into Java 8 and later. See Oracle Tutorial.

Specifically, the LocalTime and DateTimeFormatter classes.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
LocalTime localTime = LocalTime.parse("123459", formatter);

LocalTime timeIn5Seconds = localTime.plusSeconds(5);
System.out.println(timeIn5Seconds.format(formatter));

Output

123504
Ole V.V.
  • 65,573
  • 11
  • 96
  • 117
smac89
  • 26,360
  • 11
  • 91
  • 124
0

to convert string to date format...

DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");

Date date = (Date)formatter.parse(str);

to add 5 seconds

Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date according to the OBJECT

cal.add(Calendar.SECOND, 5); // adds 5 SECONDS
cal.getTime();
smac89
  • 26,360
  • 11
  • 91
  • 124
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Mar 13 '18 at 04:50
  • Please don’t teach the young ones to use the `SimpleDateFormat` class. It is not only long outdated (along with `Calendar` and `date`), it is also notoriously troublesome. And today we have so much better in [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 13 '18 at 05:24