1. 程式人生 > >JAVA 時間格式互相轉化工具類

JAVA 時間格式互相轉化工具類

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: JCccc
 * @CreateTime: 2018-09-11
 * @Description:
 */
public class TimeConversionUtil {


   //傳入long時間戳 ,轉換成格式化的String型別時間

    public  String TimeOfLongToStr(long time) {
        Date date = new Date(time);
        //定義時間的格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String strTime = sdf.format(date);
        return strTime;
    }

    //傳入String型別格式化時間,轉換成Long型別的時間戳

    public  long TimeOfStrToLong(String strTime){
        long time = 0;
        try {
            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date date = sdf.parse(strTime);
            time = date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }


    //通過LocalDateTime獲取當前格式化時間

    public String getTimeStrNow(){
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        String strTime = dtf.format(localDateTime);
        return strTime;
    }

    //獲取當前時間戳方法一

    public long getTimeLongOfClock(){
        long longTimeNow = Clock.systemDefaultZone().millis();

        return longTimeNow;
    }

    //獲取當前時間戳方法二

    public long getTimeLongOfCalendar(){
        Calendar calendar = Calendar.getInstance();
        long longTimeNow = calendar.getTimeInMillis();

        return longTimeNow;
    }

    //獲取當前時間戳方法三

    public long getTimeLongOfSystem(){
        long longTimeNow = System.currentTimeMillis();

        return longTimeNow;
    }

    //獲取當前時間戳方法四

    public long getTimeLongOfDate(){

        Date date = new Date();
        long longTimeNow = date.getTime();

        return longTimeNow;
    }


}