2019阿里云面试题,竟然现场敲代码,现在的企业越来越实在了

写一个方法,输入两个Date d1,d2,按照自然月输出,

         如:输入“2019-05-10”,“2019-10-10”

                输出如图所示:

 

需要考虑的方面:1、 正常情况:跨月,跨年

        2 、参数为null 

        3 、开始日期小于终止日期

 

代码:

package com.example.baiduface.test;

import org.junit.Test;

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

/**
 * @Author: ldk
 * @Date: 2019/7/9 20:28
 * @Describe:
 */
public class test {

    //输入两个日期,调用 A(Date d1 ,Date d2)
    @Test
    public void test() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse("2019-05-10");
        Date d2 = sdf.parse("2019-10-10");
        A(d1, d2);
    }

    public void A(Date d1, Date d2) throws ParseException {
        //判空
        if (d1 == null || d2 == null || d1.getTime() > d2.getTime()) {
            System.out.println("参数错误!!");
            return;
        }
        //当d1小于d2之前,就一直循环
        while (d1.getTime() <= d2.getTime()) {
            //根据 d1 获取当月最后一天 dmax
            Date dmax = fun2(d1);
            if (dmax.getTime() < d2.getTime()) {
                B(d1, dmax);
                //d1转化成下月第一天
                d1 = fun1(d1);
                continue;
            } else if (dmax.getTime() > d2.getTime()) {
                B(d1, d2);
                break;
            } else if (dmax.getTime() == d2.getTime()) {
                B(d1, d2);
                break;
            }
        }
    }


    //根据d1 获得 下个月第一天
    public Date fun1(Date d1) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sdf.format(d1);
        try {
            Date date = sdf.parse(dateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
            calendar.add(Calendar.MONTH, 1);
            Date time = calendar.getTime();
            return time;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    //根据d1 获得 当月最后一天
    public Date fun2(Date d1) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cale = Calendar.getInstance();
        cale.setTime(d1);
        cale.add(Calendar.MONTH, 1);
        cale.set(Calendar.DAY_OF_MONTH, 0);
        String lastday = sdf.format(cale.getTime());
        return sdf.parse(lastday);
    }

    //调用B方法输出整理好的日期
    public void B(Date d1, Date d2) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(sdf.format(d1) + " >> " + sdf.format(d2));
    }
}

 

posted @ 2019-07-09 22:04  Dkwestworld  阅读(299)  评论(0编辑  收藏  举报