新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

java中日期格式如何转换,java中日期格式有几种

发布时间:2023-11-03 22:39:55

java中日期格式如何转换

在Java中,可使用SimpleDateFormat类来进行日期格式的转换。以下是一个示例代码,演示了怎样将一个日期字符串转换成另外一种日期格式的字符串:

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

public class DateFormatExample {

    public static void main(String[] args) {
        String dateString = "2023-05⑴5";
        String sourceFormat = "yyyy-MM-dd";
        String targetFormat = "dd/MM/yyyy";

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

            Date date = sourceDateFormat.parse(dateString);
            String formattedDateString = targetDateFormat.format(date);

            System.out.println("原日期字符串:" + dateString);
            System.out.println("转换后的日期字符串:" + formattedDateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,首先定义了一个日期字符串dateString,其格式为yyyy-MM-dd。然后,定义了源日期格式sourceFormat和目标日期格式targetFormat。接下来,创建了两个SimpleDateFormat对象,用于解析和格式化日期。使用sourceDateFormat对象的parse()方法将日期字符串解析为Date对象。然后,使用targetDateFormat对象的format()方法将Date对象格式化为目标日期格式的字符串。最后,将原日期字符串和转换后的日期字符串打印出来。

运行上面的代码,输出结果以下:

原日期字符串:2023-05⑴5
转换后的日期字符串:15/05/2023

这样就完成了日期格式的转换。根据实际需求,可以修改源日期格式和目标日期格式,和要转换的日期字符串。