注意:
使用dealDateFormat方法处理(2020-11-27T02:58:41.000000Z)这类时间类型后会出现和实际时间相差8小时,所以需要在处理之前加8小时(使用hourAddNum3方法处理)
// 使用dealDateFormat处理这种类型的时间后会缺8个小时,需要加8小时
DateUtil.dealDateFormat(DateUtil.hourAddNum3("2020-11-27T02:58:41.000000Z",8))
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* @author madong
*/
public class DateUtil {
/**
* 类似2021-01-26t01:00:00.000+0000时间格式处理
* @param oldDate
* @return
*/
public static String dealDateFormat(String oldDate) {
Date date1 = null;
DateFormat df2 = null;
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
Date date = df.parse(oldDate);
SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
date1 = df1.parse(date.toString());
df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
} catch (ParseException e) {
e.printStackTrace();
}
return df2.format(date1);
}
/**
* 添加小时
* @param time
* @param hour
* @return
*/
public static String hourAddNum3(String time, Integer hour){
//标准格式
String s = "yyyy-MM-ddTHH:mm:ss.SSSZ";
//若influxdb取得的时间长度小于标准长度
if(time.length() < s.length()){
//若influxdb取得的时间无毫秒,即:yyyy-MM-ddTHH:mm:ssZ
if(time.length()==20){
time = time.substring(0,time.length()-1)+ ".000Z";
}else {
//若influxdb取得的时间有毫秒但长度不足,即:yyyy-MM-ddTHH:mm:ss.SZ或yyyy-MM-ddTHH:mm:ss.SSZ
int n = s.length() - time.length();
String sub = "";
for (int i = 0; i < n; i++) {
sub+="0";
}
time = time.substring(0,time.length()-1)+ sub + 'Z';
}
}
//若influxdb取得的时间长度大于标准长度
if(time.length() > s.length()){
time = time.substring(0, s.length() - 1) + 'Z';
}
Date newTime = null;
try{
SimpleDateFormat format;
if(time.contains(".")){
format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
}else {
format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS'Z'");
}
Date date = format.parse(time);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, hour);
newTime = calendar.getTime();
time = format.format(newTime);
}catch (Exception e){
e.printStackTrace();
}
return time;
}
}