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

前端 未结 2 1210
北荒
北荒 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.

    0 讨论(0)
  • 2021-01-06 10:29

    Here's an optimization, assuming that the input is java.util.Date wherein you can just pass java.sql.Date and java.sql.Time in since they are just its subclasses.

    public static String addToDateTime(Date date, Increment increment) throws ParseException {
        Calendar calendar = calendar.getInstance();
        calendar.clear();
        calendar.setTime(date);
    
        switch (increment) {
            case HOURLY: calendar.add(Calendar.HOUR, 1); break;
            case DAILY: calendar.add(Calendar.DATE, 1); break;
            case WEEKLY: calendar.add(Calendar.WEEK_OF_YEAR, 1); break;
            case DO_NOT_POLL: break;
        }
    
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
    }
    
    public enum Increment {
        HOURLY, DAILY, WEEKLY, DO_NOT_POLL;
    }
    

    which can be used as

    String newTimestamp = addToDateTime(timestampIn, Increment.WEEKLY);
    

    To learn more about the useful enum, check the Sun tutorial on the subject. However, as per Java 7 you should be able to switch on String.


    I however strongly agree the JodaTime advice, here's an example:

    public static String addToDateTime(Date date, Increment increment) {
        DateTime dt = new DateTime(date);
    
        switch (increment) {
            case HOURLY: dt = dt.plusHours(1); break;
            case DAILY: dt = dt.plusDays(1); break;
            case WEEKLY: dt = dt.plusWeeks(1); break;
            case DO_NOT_POLL: break;
        }
    
        return df.print(dt);
    }
    
    public enum Increment {
        HOURLY, DAILY, WEEKLY, DO_NOT_POLL;
    }
    

    The difference is admittedly not shocking, but it has more advantages as well.

    0 讨论(0)
提交回复
热议问题