JAVA判断当前日期是节假日还是工作日

Python012

JAVA判断当前日期是节假日还是工作日,第1张

你好,这个功能一般是使用一个专门的数据库表把一年的节假日都存进去来判断的。国家每年都会提前发布一年的节假日,然后我们再导入到数据库。而特殊的做法应该可以接入百度之类的接口。希望能帮到你。

package com.qms.utils

import java.io.BufferedReader

import java.io.InputStream

import java.io.InputStreamReader

import java.net.HttpURLConnection

import java.net.URL

import java.text.SimpleDateFormat

import java.util.Date

import java.util.Map

public class holiday {

/**

* @param urlAll

*:请求接口

* @param httpArg

*:参数

* @return 返回结果

*/

public static String request( String httpArg) {

String httpUrl="http://www.easybots.cn/api/holiday.php"

BufferedReader reader = null

String result = null

StringBuffer sbf = new StringBuffer()

httpUrl = httpUrl + "?d=" + httpArg

try {

URL url = new URL(httpUrl)

HttpURLConnection connection = (HttpURLConnection) url

.openConnection()

connection.setRequestMethod("GET")

connection.connect()

InputStream is = connection.getInputStream()

reader = new BufferedReader(new InputStreamReader(is, "UTF-8"))

String strRead = null

while ((strRead = reader.readLine()) != null) {

sbf.append(strRead)

sbf.append("\r\n")

}

reader.close()

result = sbf.toString()

Map<String,Object>map=JsonUtil.toMap(result)

String res=(String)map.get(httpArg)

} catch (Exception e) {

e.printStackTrace()

}

return result

}

public static void main(String[] args) {

//判断今天是否是工作日 周末 还是节假日

SimpleDateFormat f=new SimpleDateFormat("yyyyMMdd")

String httpArg=f.format(new Date())

System.out.println(httpArg)

String jsonResult = request(httpArg)

Map<String,Object>map=JsonUtil.toMap(jsonResult)

String res=(String)map.get(f.format(new Date()))

System.out.println(res)

//0 上班 1周末 2节假日

}

}

时间处理,更方便和更易读的代码角度讲,肯定要用Java8的新date api啦,由于涉及到一系列日期,所以结合Java8的Stream也是理所当然

总体思路

由于节假日每年在变,所以需要罗列出所有的节假日集合A

生成2016-01-01 至 2016-05-01所有的日期,生成日期集合B

从B中过滤掉A中的节假日

从B中过滤掉周六周日

最后把B中集合打印

结合思路,所见即所得的代码如下:

// 所有节假日的日期集合,这里你可以自己添加,只写了两个仅供参考(完成思路1)

List<LocalDate> holidays = Arrays.asList(LocalDate.parse("2016-01-01"), LocalDate.parse("2016-05-01"))

// 按照起始2016-01-01,每次递增一天的方式生成一个Stream

Stream.iterate(LocalDate.parse("2016-01-01"), localDate -> localDate.plusDays(1))

        // 按照要求的时间间隔2016-01-01 至 2016-05-01中的实际间隔天数截断Stream(完成思路2)

        .limit(ChronoUnit.DAYS.between(LocalDate.parse("2016-01-01"), LocalDate.parse("2016-05-01")))

        // 过滤其中的节假日(完成思路3)

        .filter(localDate -> !holidays.contains(localDate))

        // 过滤其中的周六

        .filter(localDate -> !DayOfWeek.SATURDAY.equals(DayOfWeek.of(localDate.get(ChronoField.DAY_OF_WEEK))))

        // 过滤其中的周日(完成思路4)

        .filter(localDate -> !DayOfWeek.SUNDAY.equals(DayOfWeek.of(localDate.get(ChronoField.DAY_OF_WEEK))))

        // 打印最后结果(完成思路5)

        .forEach(System.out::println)

打印的结果:

综上:结合新时间API的易用性+Stream处理集合的快捷性,写出代码还是很简洁的