String、Date类型时间互相转换,计算时间差

本文详细介绍如何在Java中将String类型的时间字符串转换为Date类型,并进行时间差的计算。同时,也展示了如何将Date类型转换回String类型,适用于各种日期格式的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. String类型时间转换Date,计算时间差

    /**
     * Method: String 类型时间转 Date
     */
    @Test
    public void testStringToDate() throws Exception {
        String ss = "{\"notbefore\":\"2019.11.09 15:09:00\",\"notafter\":\"2022.07.24 15:09:00\"}";
        JSONObject json = JSONObject.parseObject(ss);
        String notafter = json.getString("notafter");
        String notbefore = json.getString("notbefore");
        System.out.println("String类型时间-notafter: " + notafter);
        System.out.println("String类型时间-notbefore:" + notbefore);
        //注意格式 yyyy.MM.dd HH:mm:ss 和 String 类型对应
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        Date parse1 = sdf.parse(notafter);
        Date parse2 = sdf.parse(notbefore);
        int timeSize = (int) ((sdf.parse(notafter).getTime() - sdf.parse(notbefore).getTime()) / (1000 * 3600 * 24));
        System.out.println("Date类型时间-notafter: " + parse1);
        System.out.println("Date类型时间-notbefore:" + parse2);
        System.out.println("时间差timeSize: " + timeSize + " 天");

    }

控制台:

String类型时间-notafter: 2022.07.24 15:09:00
String类型时间-notbefore:2019.11.09 15:09:00
Date类型时间-notafter: Sun Jul 24 15:09:00 CST 2022
Date类型时间-notbefore:Sat Nov 09 15:09:00 CST 2019
时间差timeSize: 988 天

Process finished with exit code 0

 

   特别注意format的格式要与日期String的格式相匹配,再例如:

String dateStr = "2010/05/04 12:34:23";  
Date date = new Date();       
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");  
date = sdf.parse(dateStr);  

2. Date类型时间转String

    /**
     * Method: Date 类型时间转 String
     */
    @Test
    public void testDateToString() throws Exception {

        String dateStr;
        String dateStr1;
        Date date = new Date();
        //format的格式可以任意
        DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH/mm/ss");
        dateStr = sdf.format(date);
        dateStr1 = sdf2.format(date);
        System.out.println("dateStr : " + dateStr);
        System.out.println("dateStr1 : " + dateStr1);
    }

控制台:

dateStr : 2019/11/11 09:56:10
dateStr1 : 2019-11-11 09/56/10

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值