我周日的挑战是获取特定年份的工作日并将其保存到 CSV 等文件中。
我有以下代码,我面临的问题是:如何以特定格式打印日期,即 YYYYMMDD,因为代码当前打印的内容类似于 Sat Jan 19 00:00:00 CET 2019。
另外,如果我可以排除周末,并且通常是否有更好的方法可以在 Java 8 中编写更短的代码。
import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;
public class DatesInYear
{
public static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
public static void main (String[] args) throws java.lang.Exception
{
Date dt = new Date();
System.out.println(dt);
List<Date> dates = printDates("20190101","20191231");
Collections.reverse(dates);
System.out.println(dates.size());
for(Date date:dates)
{
SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
System.out.println(format1.format(date));
}
}
public static List<Date> printDates(String fromDate, String toDate)
{
ArrayList<Date> dates = new ArrayList<Date>();
try {
Calendar fromCal = Calendar.getInstance();
fromCal.setTime(dateFormat .parse(fromDate));
Calendar toCal = Calendar.getInstance();
toCal.setTime(dateFormat .parse(toDate));
while(!fromCal.after(toCal))
{
dates.add(fromCal.getTime());
fromCal.add(Calendar.DATE, 1);
}
} catch (Exception e) {
System.out.println(e);
}
return dates;
}
}
最佳答案
既然是 2020 年,你真的应该拥抱 java.time.*
API。
虽然我确信可能有一种非常巧妙的方法来获得日期之间的“工作日”,但我已经采用了蛮力方法......
LocalDate ld = LocalDate.of(2020, Month.JANUARY, 1);
LocalDate endDate = ld.plusYears(1);
// You don't "have" to put into a list, but I like to seperate my
// code responsbilities ;)
List<LocalDate> workDays = new ArrayList<>(365);
System.out.println(endDate);
while (ld.isBefore(endDate)) {
// This would be a good place for a delegate to determine if we want the specific day
// as it could then take into account public holidays
if (ld.getDayOfWeek() == DayOfWeek.SATURDAY || ld.getDayOfWeek() == DayOfWeek.SUNDAY) {
// NOOP
} else {
workDays.add(ld);
}
ld = ld.plusDays(1);
}
然后你可以简单地使用
DateTimeFormatter
格式化LocalDate
转换成您想要的格式,例如...DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMdd");
List<String> formats = workDays.stream().map(value -> value.format(format)).collect(Collectors.toList());
for (String value : formats) {
System.out.println(value);
}
关于Java 以 YYYYMMDD 格式获取一年中的所有工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60361104/