Java 如何获得3个月之前的日期

该代码示例展示了如何使用Java的Calendar类设置日期,以及进行日期之间的计算。它还包含了将秒数转换为时分秒格式的方法,并进行了日期格式化。主要操作包括获取当前日期的剩余秒数,日期的减法操作,以及日期字符串的解析和格式化。
摘要由CSDN通过智能技术生成

看好了,我只表演一次

public class Day30Test {
    public static void main(String[] args) throws ParseException {
//        int cacheTime = getTodayRemainSeconds().intValue();
//        System.out.println(cacheTime+"秒");
//        String s = secondConvertHourMinSecond(Long.valueOf(cacheTime));
//        System.out.println(s);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,-31);
        Date time = calendar.getTime();
        //Sun Oct 30 15:35:57 CST 2022
        System.out.println(calendar.getTime());
        String dateStr   = "Sun Oct 30 15:35:57 CST 2022";
        DateFormat cst = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat gmt = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
        Date dateTime = gmt.parse(dateStr);
        String dateString = cst.format(dateTime);
        System.out.println(dateString);

    }

    public static final long MILLIS_OF_DAY = 86400000;

    public static Long getTodayRemainSeconds() {
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.HOUR_OF_DAY, 0);
        ca.set(Calendar.MINUTE, 0);
        ca.set(Calendar.SECOND, 0);

        ca.setTimeInMillis(((ca.getTimeInMillis() + MILLIS_OF_DAY)/ 1000L) * 1000L);
        Date date = ca.getTime();
        return (date.getTime() - System.currentTimeMillis())/1000;
    }

    /**
     * 将秒转为时分秒格式【01:01:01】
     * @param second 需要转化的秒数
     * @return
     */
    public static String secondConvertHourMinSecond(Long second) {
        String str = "00:00:00";
        if (second == null || second < 0) {
            return str;
        }

        // 得到小时
        long h = second / 3600;
        str = h > 0 ? ((h < 10 ? ("0" + h) : h) + ":") : "00:";

        // 得到分钟
        long m = (second % 3600) / 60;
        str += (m < 10 ? ("0" + m) : m) + ":";

        //得到剩余秒
        long s = second % 60;
        str += (s < 10 ? ("0" + s) : s);
        return str;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值