简体   繁体   中英

How to add 30 minutes to java.sql.Time object?

I have this Time object:

Time myTime = java.sql.Time.valueOf("15:33:00");

How can I add 30 minutes to myTime in Java? That means the new time will be 16:03:00

 java.sql.Time myTime = java.sql.Time.valueOf("15:33:00");
 LocalTime localtime = myTime.toLocalTime();
 localtime = localtime.plusMinutes(30);
 String output = localtime.toString();

you can get localTime straight away from the java.sql.time and you can use plusMinutes in LocalTime Api to add 30 minutes. this might help you check this

Here's an easy way to do it, using java.time.LocalDateTime :

package time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalField;

/**
 * Created by Michael
 * Creation date 4/24/2016.
 * @link
 */
public class TimeDemo {

    public static void main(String[] args) {
        // Three three lines do the work
        LocalDateTime localDateTime = LocalDateTime.of(2016, 4, 24, 9, 10);
        LocalDateTime halfHourLater = localDateTime.plusMinutes(30); // Add 30 minutes
        java.sql.Time sqlDateTime = new java.sql.Time(halfHourLater.toInstant(ZoneOffset.UTC).toEpochMilli()); //
        // Printout just to check
        System.out.println(DateTimeFormatter.ofPattern("yyyy-MMM-dd hh:mm:ss.SSS").format(halfHourLater));
        System.out.println("java.time milliseconds: " + halfHourLater.toInstant(ZoneOffset.UTC).toEpochMilli());
        System.out.println("System.currentMillis  : " + System.currentTimeMillis());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM