如何将整数日期(20180525)转为YYYY-MM-DD格式?(Java)
Hey there! Great question—you absolutely don't have to rely solely on Java code for this conversion, though that's definitely a common and straightforward approach. Let's break down your options based on different scenarios:
If you're working within a Java application, here are a few reliable ways to handle the conversion:
1. Modern Java 8+ DateTime API (Recommended)
This is the best choice for Java 8 and later—thread-safe, clean, and includes built-in date validation:
int dateNumber = 20180525; // Convert integer to an 8-digit string (handles cases where numbers might be shorter) String dateString = String.format("%08d", dateNumber); // Define formatters for input and output DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd"); DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Parse and format the date LocalDate date = LocalDate.parse(dateString, inputFormatter); String formattedDate = date.format(outputFormatter); System.out.println(formattedDate); // Output: 2018-05-25
Bonus: This will throw a DateTimeParseException if the input is an invalid date (like 20181331), so you can easily handle bad data.
2. Legacy SimpleDateFormat
If you're stuck on an older Java version, this works but note it's not thread-safe:
int dateNumber = 20180525; String dateString = String.format("%08d", dateNumber); SimpleDateFormat inputFormat = new SimpleDateFormat("yyyyMMdd"); SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = inputFormat.parse(dateString); String formattedDate = outputFormat.format(date); System.out.println(formattedDate); // Output: 2018-05-25 } catch (ParseException e) { e.printStackTrace(); // Handle invalid date errors here }
3. Raw String Manipulation (Quick but No Validation)
If you're 100% sure your input is always a valid 8-digit date, you can skip date APIs entirely and just slice the string:
int dateNumber = 20180525; String dateString = String.valueOf(dateNumber); if (dateString.length() == 8) { String formattedDate = String.join("-", dateString.substring(0, 4), dateString.substring(4, 6), dateString.substring(6) ); System.out.println(formattedDate); // Output: 2018-05-25 } else { System.err.println("Invalid date length—must be 8 digits"); }
Note: This won't catch invalid dates (like 20180230), so only use this if data validity is guaranteed elsewhere.
If your integer date lives outside a Java app, there are plenty of tools to convert it without writing code:
MySQL Database: Use built-in functions to format directly in queries:
SELECT DATE_FORMAT(STR_TO_DATE(20180525, '%Y%m%d'), '%Y-%m-%d') AS formatted_date; -- Output: 2018-05-25Excel: Use a text formula to reformat the value (assuming your date is in cell A1):
=TEXT(A1,"0000-00-00")Or if it's treated as a numeric value:
=LEFT(A1,4)&"-"&MID(A1,5,2)&"-"&RIGHT(A1,2)Shell Script: Use
sedorawkto manipulate the string:date_num=20180525 formatted_date=$(echo $date_num | sed 's/\(....\)\(..\)\(..\)/\1-\2-\3/') echo $formatted_date # Output: 2018-05-25
Pick the method that fits your use case best—no need to force Java if there's a simpler tool for the job!
内容的提问来源于stack exchange,提问作者Joseph Freeman

