获取指定时间段内的日期 和 获取指定日期是星期几

来源:互联网 发布:access sql 编辑:程序博客网 时间:2024/05/16 10:22
public class Test {    public static void main(String[] args) throws ParseException {        //获取指定时间段内的日期集合        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");        List<String> l = new ArrayList<String>();        try {            Date begin = sdf.parse("2017-08-01 00:00:00");            Date end = sdf.parse("2017-09-01 00:00:00");            Calendar cal = Calendar.getInstance();            while (begin.compareTo(end) <= 0) {                l.add(sdf.format(begin));                cal.setTime(begin);                cal.add(Calendar.DAY_OF_MONTH, 1);                begin = cal.getTime();            }        } catch (ParseException e) {            e.printStackTrace();        }        System.out.println(l);
运行结果是 :
[2017-08-01, 2017-08-02, 2017-08-03, 2017-08-04, 2017-08-05, 2017-08-06, 2017-08-07, 2017-08-08,
   2017-08-09, 2017-08-10, 2017-08-11, 2017-08-12, 2017-08-13, 2017-08-14, 2017-08-15, 2017-08-16, 
2017-08-17, 2017-08-18, 2017-08-19, 2017-08-20, 2017-08-21, 2017-08-22, 2017-08-23, 2017-08-24, 
        2017-08-25, 2017-08-26, 2017-08-27, 2017-08-28, 2017-08-29, 2017-08-30, 2017-08-31, 2017-09-01]
        //获取指定日期是星期几        String str = "2017-09-16";        Calendar calendar = Calendar.getInstance();        calendar.setTime(sdf.parse(str));        int i =calendar.get(Calendar.DAY_OF_WEEK);        if(i == 1){            System.out.println("今天是星期日");        }else{            System.out.println("今天是星期"+(i-1));        }        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");        System.out.println(sdf1.format(calendar.getTime()));        SimpleDateFormat sdf2 = new SimpleDateFormat("E");        String s = sdf2.format(calendar.getTime());        System.out.println(sdf2.format(calendar.getTime()));
运行结果是:
今天是星期62017-09-16 00:00:00 星期六星期六    }}
原创粉丝点击