要将Java中的字符串类型的时间字符串转为指定格式的字符串,可以使用SimpleDateFormat类和parse()方法。以下是一个示例代码:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws ParseException {
        String timeString = "2021-09-01 12:34:56";
        String sourceFormat = "yyyy-MM-dd HH:mm:ss";
        String targetFormat = "dd/MM/yyyy HH:mm:ss";

        SimpleDateFormat sourceDateFormat = new SimpleDateFormat(sourceFormat);
        SimpleDateFormat targetDateFormat = new SimpleDateFormat(targetFormat);

        Date date = sourceDateFormat.parse(timeString);
        String targetTimeString = targetDateFormat.format(date);

        System.out.println("Source time string: " + timeString);
        System.out.println("Target time string: " + targetTimeString);
    }
}

在上述代码中,我们首先定义了一个时间字符串timeString,表示源时间字符串。然后,我们定义了源时间字符串的格式sourceFormat和目标时间字符串的格式targetFormat。我们使用SimpleDateFormat类来解析源时间字符串和格式化目标时间字符串。

首先,我们创建了一个SimpleDateFormat对象sourceDateFormat,并使用parse()方法将源时间字符串解析为Date对象。然后,我们创建了另一个SimpleDateFormat对象targetDateFormat,并使用format()方法将Date对象格式化为目标时间字符串targetTimeString

最后,我们打印源时间字符串和目标时间字符串。输出结果如下:

Source time string: 2021-09-01 12:34:56
Target time string: 01/09/2021 12:34:56

可以看到,源时间字符串被成功解析为Date对象,并且目标时间字符串按照指定格式进行了格式化

java string类型时间字符串转为指定格式字符串

原文地址: https://www.cveoy.top/t/topic/iw9m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录