Java代码中如何将字符串转换为日期格式呢?
下文笔者讲述java代码将字符串信息修改为日期格式的方法分享,如下所示
字符串转换为LocalDateTime
SimpleDateFormat修改Date
将String转换为Date并使用SimpleDateFormat更改日期格式
字符串转Date
字符串转日期对象的实现思路: jdk8及以后的版本可使用DateTimeFormatter 否则使用SimpleDateFormat更改字符串
字符串转换为LocalDateTime
使用DateTimeFormatter更改日期格式
package com.java265; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateFormatExample1 { // date format 1 private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"); // date format 2 private static final DateTimeFormatter dateFormatterNew = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy HH:mm:ss a"); public static void main(String[] args) { String date = "2022-02-5 00:00:00.0"; // string to LocalDateTime LocalDateTime ldateTime = LocalDateTime.parse(date, dateFormatter); System.out.println(dateFormatter.format(ldateTime)); // change date format System.out.println(dateFormatterNew.format(ldateTime)); } }
SimpleDateFormat修改Date
将String转换为Date并使用SimpleDateFormat更改日期格式
package com.java265;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatExample {
private static final SimpleDateFormat sdf =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
private static final SimpleDateFormat sdfNew =
new SimpleDateFormat("EEEE, MMM d, yyyy HH:mm:ss a");
public static void main(String[] args) {
String dateString = "2022-02-05 00:00:00.0";
try {
// string to date
Date date = sdf.parse(dateString);
System.out.println(sdf.format(date));
System.out.println(sdfNew.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。