郭远ing 2021-10-26 19:56 采纳率: 100%
浏览 98
已结题

Java写一个计算记录计算时间的类,有一处报错,求解


package com.my.tool;

/**
 * ClassName:TogTime
 * Package:com.my.tool
 *
 * @Date:2021/10/26 19:42;
 * @auther:guoyuan
 */
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;

public class TogTime {
    public long getTime(){
        String birthday = "2020-08-06";
        //使用SimpleDateFormat 类中的parse方法,将字符串中的date日期转换成为Date格式的出生日期
        Date date = parse(birthday);         //**parse显示错误    Unhandled exception: java.text.ParseException**
        //把date格式转化成毫秒
        long birthdaytime = date.getTime();
        //获取当前时间,将其转化为毫秒值
        Long nowtime = new Date().getTime();
        //使用当前时间毫秒值减去生日日期毫秒值
        long result = nowtime - birthdaytime;
        //把毫秒的差值转化成为天(s/1000/60/60/24)
        long days = result/1000/60/60/24;
        return days;
    }
    public static void main(String[] args) throws ParseException {
        TogTime tt = new TogTime();
        long day = tt.getTime();
        System.out.println(day);
    }
    private static Date parse(String str) throws ParseException {
        SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = d.parse(str);
        return parse;
    }
}

  • 写回答

2条回答 默认 最新

  • CSDN专家-sinJack 2021-10-26 20:00
    关注

    d.parse(str);
    解析的方法中抛出的。
    调用的地方,你需要处理这个异常,所以getTime()方法也可以选择抛出或者捕获异常。

     
    package com.my.tool;
    /**
     * ClassName:TogTime
     * Package:com.my.tool
     *
     * @Date:2021/10/26 19:42;
     * @auther:guoyuan
     */
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Scanner;
    public class TogTime {
        public long getTime() throws ParseException {
            String birthday = "2020-08-06";
            //使用SimpleDateFormat 类中的parse方法,将字符串中的date日期转换成为Date格式的出生日期
            Date date = parse(birthday);         //**parse显示错误    Unhandled exception: java.text.ParseException**
            //把date格式转化成毫秒
            long birthdaytime = date.getTime();
            //获取当前时间,将其转化为毫秒值
            Long nowtime = new Date().getTime();
            //使用当前时间毫秒值减去生日日期毫秒值
            long result = nowtime - birthdaytime;
            //把毫秒的差值转化成为天(s/1000/60/60/24)
            long days = result/1000/60/60/24;
            return days;
        }
        public static void main(String[] args) throws ParseException {
            TogTime tt = new TogTime();
            long day = tt.getTime();
            System.out.println(day);
        }
        private static Date parse(String str) throws ParseException {
            SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd");
            Date parse = d.parse(str);
            return parse;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 11月3日
  • 已采纳回答 10月26日
  • 创建了问题 10月26日