java中日期格式如何转换

45次阅读
没有评论

共计 1073 个字符,预计需要花费 3 分钟才能阅读完成。

在 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-15";
        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-15
转换后的日期字符串:15/05/2023

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

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-13发表,共计1073字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)