- 定义常量类
public class ExchangeConstants {
public static final String FORMAT = "yyyy-MM-dd HH:mm:ss";
public static final String FORMAT_T = "yyyy-MM-dd'T'HH:mm:ss";
public static final String FORMAT_Z = "EEE MMM dd HH:mm:ss Z yyyy";
}
- 代码逻辑实现
- 这里碰到的 2021-06-26T12:11:52.000+0000 这种格式, 是从数据库取出来时, 数据库对应datetime类型。
import com.example.demo.Demo.util.ExchangeConstants;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Test02 {
public static void main(String[] args) {
//MySQL识别的日期格式
String date = "2021-06-26T12:11:52.000+0000";
System.out.println(dealDateFormat(date));
//输出: 2021-06-26 12:11:52
}
/**
* 处理时间格式 2021-06-26T12:11:52.000+0000 为 yyyy-MM-dd HH:mm:ss
*/
static String dealDateFormat(String oldDate) {
Date date1 = null;
DateFormat df2 = null;
try {
DateFormat df = new SimpleDateFormat(ExchangeConstants.FORMAT_T);
Date date = df.parse(oldDate);
SimpleDateFormat df1 = new SimpleDateFormat(ExchangeConstants.FORMAT_Z, Locale.UK);
date1 = df1.parse(date.toString());
df2 = new SimpleDateFormat(ExchangeConstants.FORMAT);
} catch (Exception e) {
e.printStackTrace();
}
return df2.format(date1);
}
}
- 转载出处:https://www.cnblogs.com/justtodo/p/11979815.html 文章出自:眸色的博客