Reputation: 87
I have an initial time 12:00:00
and I need to add 144
mins to it.
The expected output is 15.24.00
(i.e, adding 2.24 hours to the initial time).
How should I update the current code given below ?
String startTime = "13:00:00";
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date date1 = null;
Date date2 = null;
try {
date1 = format.parse(startTime);
} catch (ParseException e) {
e.printStackTrace();
}
Long addition = (long) (TimeUnit.MILLISECONDS.toMinutes(date1.getTime()));
System.out.println("Difference : "+addition);
Upvotes: 0
Views: 446
Reputation: 580
You can do it in the below way:
String str = "13:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("kk:mm:ss");
LocalTime dateTime = LocalTime.parse(str, formatter).plusMinutes(144);
System.out.println(dateTime);
Upvotes: 0
Reputation: 79075
You should use a modern date-time API as follows :
import java.time.Duration;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
LocalTime time = LocalTime.parse("13:00:00").plus(Duration.ofMinutes(144));
System.out.println(time);
}
}
Output:
15:24
Check here for more information.
Upvotes: 5
Reputation: 716
Step 1:
Convert input String to java.util.Date via implementing the following logic:
public static Date getDate(String source, String format) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.parse(source);
}
Step 2:
Adding minutes to the date:
public static Date add(Date date, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, minute);
return calendar.getTime();
}
Step 3:
Now, If you want to convert java.util.Date back to String use following logic:
public static String getDate(Date date, String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
Upvotes: 1