You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中替换日期字符串的时间部分问题求助

Fixing Your String Date-Time Update

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");

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:35:45