Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This code isn't good.</p> <p>I don't understand why you're doing all this parsing of Strings to get to Date and visa versa when you have java.text.DateFormat and java.text.SimpleDateFormat to do it easily for you.</p> <p>I think this is better. See if you agree:</p> <pre><code>package com.contacts.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class DateUtils { private static final DateFormat DEFAULT_FORMAT = new SimpleDateFormat("dd-MMM-yyyy"); public static void main(String[] args) { try { Date startDate = ((args.length &gt; 0) ? DEFAULT_FORMAT.parse(args[0]) : new Date()); Date endDate = ((args.length &gt; 1) ? DEFAULT_FORMAT.parse(args[1]) : new Date()); List&lt;Date&gt; weekdays = DateUtils.getWeekdays(startDate, endDate); Calendar calendar = Calendar.getInstance(); for (Date d : weekdays) { calendar.setTime(d); int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH); int month = calendar.get(Calendar.MONTH); int year = calendar.get(Calendar.YEAR); // System.out.println(DEFAULT_FORMAT.format(d)); System.out.println("day: " + dayOfMonth + " month: " + (month+1) + " year: " + year); } } catch (ParseException e) { e.printStackTrace(); } } public static List&lt;Date&gt; getWeekdays(Date startDate, Date endDate) { List&lt;Date&gt; weekdays = new ArrayList&lt;Date&gt;(); if ((startDate == null) || (endDate == null)) return weekdays; if (startDate.equals(endDate)) { if (isWeekday(startDate)) { weekdays.add(startDate); } } else if (startDate.after(endDate)) { weekdays = getWeekdays(endDate, startDate); } else { Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); Date d = startDate; while (endDate.equals(d) || endDate.after(d)) { if (isWeekday(d)) { weekdays.add(d); } calendar.add(Calendar.DATE, 1); d = calendar.getTime(); } } return weekdays; } public static boolean isWeekday(Date d) { if (d == null) return false; Calendar calendar = Calendar.getInstance(); calendar.setTime(d); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); return ((dayOfWeek &gt;= Calendar.MONDAY) &amp;&amp; (dayOfWeek &lt;= Calendar.FRIDAY)); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload