java時間工具類

HssC發表於2020-11-07
package com.han.common.util;

import com.han.common.entity.TimePattern;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TimeUtil {

    /**
     * 獲取當前時間的long格式,秒數
     * @return
     */
    public static long getLongTime(){
        Date date = new Date();
        long time = date.getTime();
        return time/1000;
    }

    /**
     * 獲得當前時間
     * @return 2020-10-27 16:47:16
     */
    public static String getTime() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = LocalDateTime.now().format(formatter);
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String time = simpleDateFormat.format(new Date());
        return format;
    }

    /**
     * 獲得當前時間,秒數置為0
     * @return 2020-10-27 16:47:16 轉換為 2020-10-27 16:47:00
     */
    public static String getRoundTime() {
        String time = TimeUtil.getTime();
        String substring = time.substring(0, 17);
        substring = substring + "00";
        return substring;
    }

    /**
     * 傳入秒數格式的時間,轉換為指定日期格式
     * @param second  秒數(非毫秒數),例:1603788436
     * @param pattern TimePattern.LONG_PATTERN.getPattern()
     * @return 2020-10-27 16:47:16
     */
    public static String secondToDate(long second, String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(second * 1000);
        Date time = calendar.getTime();
        SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        String date = dateFormat.format(time);
        return date;
    }

    /**
     * 將指定日期的字串轉化為秒數
     * @param date
     * @return
     * @throws Exception
     */
    public static long dateToSecond(String date) throws Exception{
        int length = date.length();
        SimpleDateFormat dateFormat;
        if (length>10){
            dateFormat=new SimpleDateFormat(TimePattern.LONG_PATTERN.getPattern());
        }else {
            dateFormat=new SimpleDateFormat(TimePattern.SHORT_PATTERN.getPattern());
        }
        long second = dateFormat.parse(date).getTime()/1000;
        return second;
    }

    /**
     * 將秒數轉化為時間差
     * @param seconds 900610秒
     * @return map={days,hours,minutes,seconds}
     */
    public static Map secondToDays(long seconds){
        long days = (seconds) / (24 * 3600);
        long hours = (seconds) % (24 * 3600) / 3600;
        long minutes = (seconds) % 3600 / 60;
        long second = (seconds) % 60;
        HashMap<String, Long> map = new HashMap<>();
        map.put("days",days);
        map.put("hours",hours);
        map.put("minutes",minutes);
        map.put("seconds",second);
        return map;
    }

}

相關文章