开发者

Calculate number of weekend days records in array

开发者 https://www.devze.com 2023-02-03 05:30 出处:网络
I have a String Array which is contain dates that read from a CSV file. Now I want to count how many weekend days are in that array. But in my array there are some dates are duplicated. Here shows par

I have a String Array which is contain dates that read from a CSV file.

Now I want to count how many weekend days are in that array. But in my array there are some dates are duplicated. Here shows part of the data that is containing in my Array.

12/2/2010

12/3/2010

12/5/2010

12/10/2010

12/5/2010

12/13/2010

12/14/2010

12/12/2010

In this data set 12/5/2010 is Sunday (but there are two records) & 12/12/2010 is Saturday (has One record). In output, I want to print number o开发者_运维百科f weekend days in this array using java. Compared to this example the Answer should be 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);
}


First, you need to write a method that determines if a given Date is a weekend or not:

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;
}

Then, you need to define a DateFormat, so that you can parse a date String into a java.util.Date. Finally, you can use a Set to assure every weekend you find is not going to be duplicated:

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
}


I would say you need to first remove duplicates and then check which of them are weekend days:

Set<String> set = new HashSet<String>( Arrays.asList(yourArrayOfDateStrings) );
DateFormat df = new SimpleDateFormat(yourDatePattern);
Calendar calendar = Calendar.getInstance();
int weekendDays = 0;
for (String dateString : set) {
    calendar.setTime( df.parse(dateString) );
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
        weekendDays++;
    }
}


I don't use java date, ever!
I agree with Costi Ciudatu, use a Set to remove duplicates.

:) please to send you teh codez using JodaTime

import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.DateTimeField;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

public class Dates
{
    static String[] localTestDate = new String[] {"12/2/2010", "12/3/2010", "12/5/2010", "12/10/2010", "12/5/2010", "12/13/2010", "12/14/2010", "12/12/2010"};

    static DateTimeFormatter dateFactory = DateTimeFormat.forPattern("MM/d/yyyy");

    public static void main(String[] args)
    {
//      final Set<DateTime> uniqueDates = generateUniqueDates(localTestDate);

        final Set<DateTime> uniqueDates = generateUniqueDates(readCommonSeparatedFile(args[0]));


        int numberOfWeekendDates = 0;
        for(DateTime date : uniqueDates)
        {
            if(isWeekend(date)) numberOfWeekendDates++;
        }

        System.out.println("There are " + numberOfWeekendDates  + " weekend days in your list.");
    }

    private static boolean isWeekend(DateTime dateTime)
    {
        return (DateTimeConstants.SATURDAY == dateTime.dayOfWeek().get() || DateTimeConstants.SUNDAY == dateTime.dayOfWeek().get());
    }

    private static String[] readCommonSeparatedFile(final String fileName)
    {
        FileInputStream fileInputStream = null;

        String[] result = null;

        try
        {
            fileInputStream = new FileInputStream(fileName);

            final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

            while (bufferedReader.ready())
            {
                String line = bufferedReader.readLine();

                result = line.split(",");
            }
        }
        catch (IOException e)
        {
            //log error some where

            throw new RuntimeException("aw, snap!");
        }

        return result;
    }

    private static Set<DateTime> generateUniqueDates(final String[] dates)
    {
        final Set<DateTime> dateTimes = new HashSet<DateTime>();

        for (String date : dates)
        {
            dateTimes.add(dateFactory.parseDateTime(date).toDateTime());
        }

        return dateTimes;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消