如何计算dd-MMM-yy HH:mm格式日期的差值?代码报错求助
Let's work through the issues in your code step by step—you've got a couple of small but critical mistakes with date types, formatting, and value handling that are causing the error.
Key Problems in Your Code
Wrong date type choice
You're usingLocalDate, which only stores year/month/day, but your input date includes a time component (10:24 AM). You need to useLocalDateTimeto capture the full date-time information.Incorrect formatter pattern
Your example date has anAMmarker, but your pattern usesHH:mm(24-hour format, which doesn't support AM/PM). The correct pattern should bedd-MMM-yy hh:mm a:hh= 12-hour clock formata= matches the AM/PM suffix
Also, addLocale.ENGLISHto the formatter to ensure month abbreviations likeaprare parsed correctly (avoids locale-specific parsing errors).
Invalid
nowassignmentdtf.format(now)returns aString, which can't be assigned back to aLocalDatevariable. You don't need to format the current date-time to calculate the difference—just use the rawLocalDateTime.now()value.Parameter order in
between()ChronoUnit.DAYS.between(start, end)returns the number of days from the start date to the end date. If you passnowfirst, you'll get a negative number ifopenis in the past. Swap the order to get a positive elapsed day count.
Corrected Code
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.Locale; public class DateDiffCalculator { public static void main(String[] args) { // Example input date string String openTime = "25/apr/18 10:24 AM"; // Formatter with correct pattern and English locale for month parsing DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yy hh:mm a", Locale.ENGLISH); // Parse input to LocalDateTime (includes date + time) LocalDateTime open = LocalDateTime.parse(openTime, dtf); // Get current date-time directly (no formatting needed for calculation) LocalDateTime now = LocalDateTime.now(); // Calculate elapsed days from open date to now long elapsedDays = ChronoUnit.DAYS.between(open, now); System.out.println("Elapsed days: " + elapsedDays); } }
Bonus: If You Only Need Date (No Time) Difference
If you want to ignore the time component and calculate the difference between just the dates, convert both LocalDateTime objects to LocalDate:
LocalDate openDate = open.toLocalDate(); LocalDate nowDate = now.toLocalDate(); long elapsedDays = ChronoUnit.DAYS.between(openDate, nowDate);
内容的提问来源于stack exchange,提问作者A_Elric

