1. 程式人生 > 其它 >Java處理特殊時間格式 2021-06-26T12:11:52.000+0000 轉為常見格式 2021-06-26 12:11:52

Java處理特殊時間格式 2021-06-26T12:11:52.000+0000 轉為常見格式 2021-06-26 12:11:52

  1. 定義常量類
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";
}

  1. 程式碼邏輯實現
    • 這裡碰到的 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);
    }
}

  1. 轉載出處:https://www.cnblogs.com/justtodo/p/11979815.html 文章出自:眸色的部落格