0
点赞
收藏
分享

微信扫一扫

java 时间格式转换的几个方法

计算时间差

    /**
     * 计算时间差
     *
     * @param endTime 最后时间
     * @param startTime 开始时间
     * @return 时间差(天/小时/分钟)
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

获取当前的时间戳

    //获取当前时间的时间戳
    public static String getNowTimeStr(){
         return  Calendar.getInstance().getTimeInMillis() / 1000 + "";
    }
    //获取当前年份
    public static int getYear(){
    Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        return year;
    }

时间戳转时间格式

    /*
    * 时间戳转时间格式
     */
    public static String timestampToDateStr(String timestamp){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String sd = sdf.format(new Date(Long.valueOf(timestamp) * 1000)); // 时间戳转换日期
        return sd;
    }

获取当天开始时间

    //获取当天开始时间
    public static Date getNowDayStartTime(){
        Calendar currentDate = Calendar.getInstance();
        currentDate.set(Calendar.HOUR_OF_DAY, 0);
        currentDate.set(Calendar.MINUTE, 0);
        currentDate.set(Calendar.SECOND, 0);
        return currentDate.getTime();
    }

当前时间增加月份

//当前时间增加一个月 2个月
    public static String addMonthSetNowTime(Date date,Integer num){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, num);//增加一个月
        System.out.println("增加月份后的日期:"+calendar.getTime());//计算两个日期相差的天数long intervalMilli = oDate.getTime() - fDate.getTime();
        String s = parseDateToStr("yyyy-MM-dd HH:mm:ss", calendar.getTime());
        return s;
    }

举报

相关推荐

0 条评论