Java新手求助:基于本地时区计算目的地时间的实现问题
Hey there! Let's work through your Java time conversion problem step by step. I can see you're trying to calculate the destination time based on a time difference from your home timezone, but there are a few key issues in your code that are preventing it from running correctly. Let's break them down and fix them together.
The Issues in Your Current Code
- Uncaught
ParseException: Theparse()method fromSimpleDateFormatthrows a checked exception that you need to handle (either with atry-catchblock or by declaring it in the method signature). - Undefined variable
diff1: You referenceddiff1in your code but never declared or initialized it — you meant to use theaddhoursvariable you got from user input instead. Dateclass has noplusHours()method: The oldjava.util.Dateclass doesn't have this method. Instead, we should use Java 8+'s modernjava.timeAPI, which is far more intuitive and reliable for date/time operations.
Corrected Code Using Modern Java Time API
import java.time.LocalTime; import java.time.format.DateTimeFormatter; import java.util.Scanner; public class TripPlanner { public static void main(String[] args) { Scanner input = new Scanner(System.in); timeDiff(input); } // Time Difference Method public static void timeDiff(Scanner input) { System.out.print("What is the time difference, in hours, between your home and your destination? "); int addHours = input.nextInt(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm"); LocalTime midnight = LocalTime.parse("24:00", formatter); LocalTime noon = LocalTime.parse("12:00", formatter); // Add the time difference to home times LocalTime destinationMidnight = midnight.plusHours(addHours); LocalTime destinationNoon = noon.plusHours(addHours); System.out.println("That means that when it is midnight at home, it will be " + destinationMidnight.format(formatter) + " at your destination."); System.out.println("And when it is noon at home, it will be " + destinationNoon.format(formatter) + " at your destination."); System.out.println("**********************"); } }
Key Changes Explained
- Switched to
java.time.LocalTime: This class is designed specifically for handling time without dates, which is perfect for your use case. It has built-in methods likeplusHours()that make time arithmetic straightforward. - Used
DateTimeFormatter: Replaced the outdatedSimpleDateFormatwith this modern formatter, which is thread-safe and has better error handling. - Fixed variable references: Replaced the undefined
diff1with your user-inputaddHoursvariable. - Handled parsing implicitly: The
LocalTime.parse()method can throw aDateTimeParseException, but since it's an unchecked exception, you don't need to explicitly catch it for a simple test project (though you could add atry-catchif you want to handle invalid time inputs gracefully). - Formatted output properly: Used
format(formatter)to display the resulting times in theHH:mmformat instead of the defaultLocalTimestring representation.
Bonus Tip
If you ever need to work with full dates and time zones (not just time differences), the java.time API has classes like ZonedDateTime that can handle time zone conversions directly (e.g., converting from America/New_York to Europe/London) without manually calculating hour differences. It's worth exploring once you're comfortable with basic time operations!
内容的提问来源于stack exchange,提问作者Deepak

