2021-01-09T18:00:00.000Z格式時間存資料庫,欄位型別為datetime,直接出現報錯
阿新 • • 發佈:2021-02-10
技術標籤:java實戰
1.前端使用的elementui的<el-date-picker ,傳入的時間值為2021-01-09T18:00:00.000Z格式
2.需要將格式進行轉換,才能存入資料庫datetime型別的欄位,在後端程式碼寫一個工具類,需要轉換時直接呼叫就可以了
import org.apache.commons.lang3.StringUtils; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; //將"yyyy-MM-dd'T'HH:mm:ss.SSS Z"格式日期轉換為"yyyy-MM-dd HH:DD:MM"格式 public class DateUtil { public static Date transferDateFormat(String oldDateStr) { if (StringUtils.isBlank(oldDateStr)){ return null; } Date date = null; Date date1 = null; String dateStr = null; try { dateStr = oldDateStr.replace("Z", " UTC");//是空格+UTC DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z"); date1 = df.parse(dateStr); SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK); date = df1.parse(date1.toString()); } catch (ParseException e) { e.printStackTrace(); } return date; } }
3.呼叫方式