我有一个字符串数组,其中包含从 CSV 文件读取的日期。
现在我想计算该数组中有有多少个周末。但在我的数组中有一些日期是重复的。这里显示了我的数组中包含的部分数据。
12/2/2010
12/3/2010
12/5/2010
12/10/2010
12/5/2010
12/13/2010
12/14/2010
12/12/2010
在此数据集中,12/5/2010 是星期日(但有两条记录)&12/12/2010 是星期六(有 1 条记录)。在输出中,我想使用 java 打印此数组中的周末天数。与此示例相比,答案应为 2。
FileInputStream fis=new FileInputStream("c:/cdr2.csv");
InputStreamReader isr=new InputStreamReader(fis);
BufferedReader bf = new BufferedReader(isr);
while (bf.ready()) {
String line = bf.readLine();
String[] values=line.split(",");
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/d/yyyy");
Date date = simpleDateFormat.parse(values[2]);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
}
最佳答案
首先,您需要编写一个方法来确定给定的日期
是否是周末:
public static boolean isWeekend(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
return dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY;
}
然后,你需要定义一个DateFormat
,这样您就可以将日期 String
解析为 java.util.Date
。最后,您可以使用 Set
确保您发现的每个周末都不会重复:
public static void main(String[] args) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String[] dates = { "12/2/2010", "12/3/2010", "12/5/2010", "12/10/2010", "12/5/2010", "12/13/2010", "12/14/2010", "12/12/2010" };
Set<String> weekends = new HashSet<String>();
for (String dt : dates) {
Date date = dateFormat.parse(dt);
if (isWeekend(date)) {
weekends.add(dt);
}
}
System.out.println("There are " + weekends.size() + " distinct weekends."); // 2
}
关于java - 计算数组中周末天数记录的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4647703/