My Sunday challenge is to get and persist working days in a particular year to a CSV, etc file.
I have following code and the problem I am facing is : how to print dates in a specific format i.e. YYYYMMDD as the code currently prints something like Sat Jan 19 00:00:00 CET 2019.
Also, if I can exclude week-ends and generally if there is a better way to write a much shorter code in 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;
}
}