zoukankan      html  css  js  c++  java
  • 自定义时间工具类

    package com.jredu.ch10;

    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class DateUtil {

    /**
    * 返回两个日期之间的相差天数
    *
    * @param d1
    * @param d2
    * @param patten
    * @return
    */
    public static int diffDay(String d1, String d2, String patten) {
    int day = 0;
    SimpleDateFormat format = new SimpleDateFormat(patten);
    Date date1 = null;
    Date date2 = null;
    try {
    date1 = format.parse(d1);
    date2 = format.parse(d2);
    long m = Math.abs(date1.getTime() - date2.getTime());
    day = (int) (m / 1000 / 60 / 60 / 24);
    } catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    return day;
    }

    /**
    * 毫秒转日期
    *
    * @param m
    * @return
    */
    public static Date getDate(long m) {
    return new Date(m);
    }

    /**
    * 返回今天的日期
    */
    public static Date getCurrentDate() {
    return new Date();
    }

    /**
    * 返回当前日期加减后的日期
    *
    * @param isPlus
    * @param day
    * @return
    */
    public static Date getChangeDate(boolean isPlus, int day) {
    // System.currentTimeMillis()获取当前时间的时间戳(自1970/01/01 00:00:00开始到当前经历的毫秒数)
    long currentTime = System.currentTimeMillis();
    long changeTime = 0;
    if (isPlus) {
    // 添加日期
    changeTime = currentTime + (day * 24 * 60 * 60 * 1000);
    } else {
    // 减少日期
    changeTime = currentTime - (day * 24 * 60 * 60 * 1000);
    }
    return new Date(changeTime);
    }

    /**
    * 返回指定日期的加减天数
    *
    * @param isPlus
    * @param day
    * @param date
    * @return
    */
    public static Date getChangeDate(boolean isPlus, int day, Date date) {
    long time = date.getTime();
    long changeTime = 0;
    if (isPlus) {
    // 添加日期
    changeTime = time + (day * 24 * 60 * 60 * 1000);
    } else {
    // 减少日期
    changeTime = time - (day * 24 * 60 * 60 * 1000);
    }
    return new Date(changeTime);
    }

    /**
    * 日期格式化
    *
    * @param date
    * @param format
    * @return
    */
    public static String getFormatDate(Date date, String format) {
    // 创建格式化日期对象
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    // 将日期格式化后返回格式化字符串
    return sdf.format(date);
    }

    }

  • 相关阅读:
    ThinkPHP3.2 整合支付宝RSA加密方式
    代码风格规范
    Mac下安装composer
    MAC 下安装RabbitMQ
    Redis配置
    git 分支
    PHP常用数组操作方法汇总
    php 不用第三个变量 交换两个变量的值汇总
    PHP配置错误信息回报的等级
    Apache同一个IP上配置多域名
  • 原文地址:https://www.cnblogs.com/a5513633/p/6721405.html
Copyright © 2011-2022 走看看