[Notas pessoais] Ferramenta de conversão de tempo

	日常我们java开发中所需的时间转换工具:时间戳转年月日、时间戳转年月日时分秒、或者年月日等转时间戳。提高代码的复用性和开发效率,时常会将这些封装为工具类。网上也有很多类似的工具类,下面是我自己常用的工具类。

- Ferramentas

/**
 * @author ZBQ
 * @Classname: DateFormatUtil
 * @Description:  时间转换工具类
 * @date 2022-09-26 12:57
 */
public class DateFormatUtil {
    
    
    private static final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private static final DateTimeFormatter dtfFull = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 字符串转时间戳
     * @param dtStr
     * @param isFull 是否为当日0点 false为当日0点
     * @return
     */
    public static Long toTs(String dtStr, boolean isFull) {
    
    

        LocalDateTime localDateTime = null;
        if (!isFull) {
    
    
            dtStr = dtStr + " 00:00:00";
        }
        localDateTime = LocalDateTime.parse(dtStr, dtfFull);

        return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 字符串转时间戳
     * @param dtStr 默认为false 转时间戳为当日0点
     * @return
     */
    public static Long toTs(String dtStr) {
    
    
        return toTs(dtStr, false);
    }

    /**
     * 时间戳转年月日格式
     * @param ts
     * @return
     */
    public static String toDate(Long ts) {
    
    
        Date dt = new Date(ts);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(dt.toInstant(), ZoneId.systemDefault());
        return dtf.format(localDateTime);
    }

    /**
     * 时间戳转年月日时分秒格式
     * @param ts
     * @return
     */
    public static String toYmdHms(Long ts) {
    
    
        Date dt = new Date(ts);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(dt.toInstant(), ZoneId.systemDefault());
        return dtfFull.format(localDateTime);
    }

    public static void main(String[] args) {
    
    
        System.out.println(toYmdHms(System.currentTimeMillis()));
    }

}

Acho que você gosta

Origin blog.csdn.net/m0_49303490/article/details/128190424
Recomendado
Clasificación