What is the best way to increment a Java.sql.date / time?

前端 未结 2 1209
北荒
北荒 2021-01-06 10:01

I have an issue where I have a MySQL database storing dates and times in separate columns. However, in Java code I need to increment the resulting timestamp for a date and t

2条回答
  •  执念已碎
    2021-01-06 10:27

    You can use Joda time. Then, you can use DateTime's plusHours, plusDays, and plusWeeks. For parsing, there is DateTimeFormat and DateTimeFormatter. Something like:

    DateTimeFormatter fmt = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss");
    DateTime dt = fmt.parseDateTime(timestampin);
    
    if (increment.equals("HOURLY")) {
        dt = dt.plusHours(1);
    }
    else if (increment.equals("DAILY")) {
        dt = dt.plusDays(1);
    }
    else  if (increment.equals("WEEKLY")) {
        dt = dt.plusWeeks(1);
    }
    
    String timestampOut = fmt.print(dt);
    

    You can probably use something like:

    DateTime dt = new DateMidnight(sqlDate).plus(Period.millis(sqlTime.getTime()));
    

    That assumes the sql.Time represents the number of milliseconds since midnight.

提交回复
热议问题