Java中替换日期字符串的时间部分问题求助
Hey there! Let's get that date string modified correctly. Your initial approach using split is on the right track, but there's a small issue with how you're using replace. Let's break down a few straightforward ways to solve this:
1. The Simplest Approach: Direct String Concatenation
Since you already split the original string into date and time parts, you don't need to mess with replacing the time portion—just combine the date part with your desired time directly:
String date = "2018-03-21 00:00:00.0"; String[] parts = date.split(" "); // Combine the date segment with your target time String newDateStr = parts[0] + " 23:18:19"; System.out.println(newDateStr); // Output: 2018-03-21 23:18:19
2. Fixing Your replace Method
If you want to stick with using replace, your original code had syntax issues (wrong quote type, incorrect replacement target). Here's how to adjust it:
String date = "2018-03-21 00:00:00.0"; String[] parts = date.split(" "); // Replace the entire time segment in the original string String newDateStr = date.replace(parts[1], "23:18:19"); System.out.println(newDateStr);
Or you could skip splitting entirely and directly replace the known time value:
String newDateStr = date.replace("00:00:00.0", "23:18:19");
3. Robust, Production-Grade Approach (Recommended)
For real-world code, raw string manipulation can break if the input date format ever changes (e.g., different millisecond precision). Instead, use Java's built-in java.time date-time API to safely parse and modify the date:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeUpdateExample { public static void main(String[] args) { String originalDateStr = "2018-03-21 00:00:00.0"; // Define the format of your input string DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); // Parse the string into a LocalDateTime object LocalDateTime dateTime = LocalDateTime.parse(originalDateStr, inputFormatter); // Update the time to 23:18:19 LocalDateTime updatedDateTime = dateTime.withHour(23) .withMinute(18) .withSecond(19); // Define the format for your output (no milliseconds) DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String updatedDateStr = updatedDateTime.format(outputFormatter); System.out.println(updatedDateStr); // Output: 2018-03-21 23:18:19 } }
This method handles edge cases and format changes much more reliably than string operations.
内容的提问来源于stack exchange,提问作者Cyndi

