javajava-timemilliseconds

LocalDateTime add millisecond


I want to increase the millisecond value with LocalDateTime. I used plusNanos because I didn't have plusmillisecond. I wonder if this is the right way. I'm using JDK 1.8. I also want to know if there is a plus millisecond function in later versions.

DateTimeFormatter f = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
LocalDateTime ldt = LocalDateTime.parse("2022-01-01 00:00:00.123",f);
        
System.out.println(ldt.format(f));
        
ldt = ldt.plusNanos(1000000);
        
System.out.println(ldt.format(f));
2022-01-01 00:00:00.123
2022-01-01 00:00:00.124

Solution

  • Adding nanoseconds is a completely valid way of doing this. If you want a solution that is more self-explanatory, you can use LocalDateTime#plus(long, TemporalUnit):

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
    
    public static void main(String[] args) {
        LocalDateTime localDateTime = LocalDateTime.parse("2022-01-01 00:00:00.123", FORMATTER);
        localDateTime = localDateTime.plus(1L, ChronoUnit.MILLIS);
        //         How much you are adding ^              ^ What you are adding
    
        System.out.println(FORMATTER.format(localDateTime));
    }
    

    The TemporalUnit parameter explains exactly what you are adding to the the timestamp, thus making your code more easily understandable to other programmers who may be viewing it. It also takes care of the unit conversions behind the scenes, so there is less margin for human error and your code is not cluttered with math.