Java 日历获取工作日不起作用

发布于 2024-09-02 23:02:09 字数 3523 浏览 3 评论 0原文

我试图让它输出 2010 年 5 月 16 日(星期日)和 2010 年 5 月 25 日(星期二)之间的所有工作日(星期一至星期五)。正确的输出应该是 17,18,19,20,21,24,25。但是,我得到的结果是 17,18,19,20,21,17,18,19。其他方法只是分割日期所在的字符串

import java.util.*;
public class test
{
    public static void main(String[] args) {

        String startTime = "5/16/2010 11:44 AM";
        String endTime = "5/25/2010 12:00 PM";
        GregorianCalendar startCal = new GregorianCalendar();
        startCal.setLenient(true);
        String[] start = splitString(startTime);   
        //this sets year, month day
        startCal.set(Integer.parseInt(start[2]),Integer.parseInt(start[0])-1,Integer.parseInt(start[1]));
        startCal.set(GregorianCalendar.HOUR, Integer.parseInt(start[3]));
        startCal.set(GregorianCalendar.MINUTE, Integer.parseInt(start[4]));
        if (start[5].equalsIgnoreCase("AM")) { startCal.set(GregorianCalendar.AM_PM, 0); }
        else { startCal.set(GregorianCalendar.AM_PM, 1); }

        GregorianCalendar endCal = new GregorianCalendar();
        endCal.setLenient(true);
        String[] end = splitString(endTime);
        endCal.set(Integer.parseInt(end[2]),Integer.parseInt(end[0])-1,Integer.parseInt(end[1]));
        endCal.set(GregorianCalendar.HOUR, Integer.parseInt(end[3]));
        endCal.set(GregorianCalendar.MINUTE, Integer.parseInt(end[4]));
        if (end[5].equalsIgnoreCase("AM")) { endCal.set(GregorianCalendar.AM_PM, 0); }
        else { endCal.set(GregorianCalendar.AM_PM, 1); }


        for (int i = startCal.get(Calendar.DATE); i < endCal.get(Calendar.DATE); i++)
        {
            startCal.set(Calendar.DATE, i);
            startCal.set(Calendar.DAY_OF_WEEK, i);
            if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
            {
                System.out.println("\t" + startCal.get(Calendar.DATE));
            }
        }
    }

    private static String[] splitDate(String date)
    {
        String[] temp1 = date.split(" "); // split by space
        String[] temp2 = temp1[0].split("/"); // split by /
        //5/21/2010 10:00 AM
        return temp2; // return 5 21 2010 in one array
    }

    private static String[] splitTime(String date)
    {
        String[] temp1 = date.split(" "); // split by space
        String[] temp2 = temp1[1].split(":"); // split by :
        //5/21/2010 10:00 AM
        String[] temp3 = {temp2[0], temp2[1], temp1[2]};
        return temp3; // return 10 00 AM in one array
    }

    private static String[] splitString(String date)
    {
        String[] temp1 = splitDate(date);
        String[] temp2 = splitTime(date);
        String[] temp3 = new String[6];
        return dateFill(temp3, temp2[0], temp2[1], temp2[2], temp1[0], temp1[1], temp1[2]);
    }

    private static String[] dateFill(String[] date, String hours, String minutes, String ampm, String month, String day, String year) {
        date[0] = month;
        date[1] = day;
        date[2] = year;
        date[3] = hours;
        date[4] = minutes;
        date[5] = ampm;
        return date;
    }

    private String dateString(String[] date) {
        //return month+" "+day+", "+year+" "+hours+":"+minutes+" "+ampm
        //5/21/2010 10:00 AM
        return date[3]+"/"+date[4]+"/ "+date[5]+" "+date[0]+":"+date[1]+" "+date[2];
    }
}

I am trying to get this to output all the weekdays (MON-FRI) between 5/16/2010 (a sunday) and 5/25/2010 (a tuesday). The correct output should be 17,18,19,20,21,24,25. However, the result im getting is 17,18,19,20,21,17,18,19. The other methods just split up the string the date is in

import java.util.*;
public class test
{
    public static void main(String[] args) {

        String startTime = "5/16/2010 11:44 AM";
        String endTime = "5/25/2010 12:00 PM";
        GregorianCalendar startCal = new GregorianCalendar();
        startCal.setLenient(true);
        String[] start = splitString(startTime);   
        //this sets year, month day
        startCal.set(Integer.parseInt(start[2]),Integer.parseInt(start[0])-1,Integer.parseInt(start[1]));
        startCal.set(GregorianCalendar.HOUR, Integer.parseInt(start[3]));
        startCal.set(GregorianCalendar.MINUTE, Integer.parseInt(start[4]));
        if (start[5].equalsIgnoreCase("AM")) { startCal.set(GregorianCalendar.AM_PM, 0); }
        else { startCal.set(GregorianCalendar.AM_PM, 1); }

        GregorianCalendar endCal = new GregorianCalendar();
        endCal.setLenient(true);
        String[] end = splitString(endTime);
        endCal.set(Integer.parseInt(end[2]),Integer.parseInt(end[0])-1,Integer.parseInt(end[1]));
        endCal.set(GregorianCalendar.HOUR, Integer.parseInt(end[3]));
        endCal.set(GregorianCalendar.MINUTE, Integer.parseInt(end[4]));
        if (end[5].equalsIgnoreCase("AM")) { endCal.set(GregorianCalendar.AM_PM, 0); }
        else { endCal.set(GregorianCalendar.AM_PM, 1); }


        for (int i = startCal.get(Calendar.DATE); i < endCal.get(Calendar.DATE); i++)
        {
            startCal.set(Calendar.DATE, i);
            startCal.set(Calendar.DAY_OF_WEEK, i);
            if (startCal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY || startCal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY)
            {
                System.out.println("\t" + startCal.get(Calendar.DATE));
            }
        }
    }

    private static String[] splitDate(String date)
    {
        String[] temp1 = date.split(" "); // split by space
        String[] temp2 = temp1[0].split("/"); // split by /
        //5/21/2010 10:00 AM
        return temp2; // return 5 21 2010 in one array
    }

    private static String[] splitTime(String date)
    {
        String[] temp1 = date.split(" "); // split by space
        String[] temp2 = temp1[1].split(":"); // split by :
        //5/21/2010 10:00 AM
        String[] temp3 = {temp2[0], temp2[1], temp1[2]};
        return temp3; // return 10 00 AM in one array
    }

    private static String[] splitString(String date)
    {
        String[] temp1 = splitDate(date);
        String[] temp2 = splitTime(date);
        String[] temp3 = new String[6];
        return dateFill(temp3, temp2[0], temp2[1], temp2[2], temp1[0], temp1[1], temp1[2]);
    }

    private static String[] dateFill(String[] date, String hours, String minutes, String ampm, String month, String day, String year) {
        date[0] = month;
        date[1] = day;
        date[2] = year;
        date[3] = hours;
        date[4] = minutes;
        date[5] = ampm;
        return date;
    }

    private String dateString(String[] date) {
        //return month+" "+day+", "+year+" "+hours+":"+minutes+" "+ampm
        //5/21/2010 10:00 AM
        return date[3]+"/"+date[4]+"/ "+date[5]+" "+date[0]+":"+date[1]+" "+date[2];
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

世界和平 2024-09-09 23:02:09

startCal.set(Calendar.DAY_OF_WEEK, i); 每 7 个循环就会将日期向后翻转一次。

startCal.set(Calendar.DAY_OF_WEEK, i); Will flip flip your date back every 7 loops.

不打扰别人 2024-09-09 23:02:09

这段代码不好。

我不明白为什么当您有 java.text.DateFormat 和 java.text.SimpleDateFormat 可以轻松地为您完成所有这些字符串解析以获取日期时,反之亦然。

我认为这样更好。看看你是否同意:

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 > 0) ? DEFAULT_FORMAT.parse(args[0]) : new Date());
            Date endDate   = ((args.length > 1) ? DEFAULT_FORMAT.parse(args[1]) : new Date());

            List<Date> 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<Date> getWeekdays(Date startDate, Date endDate)
    {
        List<Date> weekdays = new ArrayList<Date>();

        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 >= Calendar.MONDAY) && (dayOfWeek <= Calendar.FRIDAY));
    }
}

This code isn't good.

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.

I think this is better. See if you agree:

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 > 0) ? DEFAULT_FORMAT.parse(args[0]) : new Date());
            Date endDate   = ((args.length > 1) ? DEFAULT_FORMAT.parse(args[1]) : new Date());

            List<Date> 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<Date> getWeekdays(Date startDate, Date endDate)
    {
        List<Date> weekdays = new ArrayList<Date>();

        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 >= Calendar.MONDAY) && (dayOfWeek <= Calendar.FRIDAY));
    }
}
孤星 2024-09-09 23:02:09

我不知道这是否是您的代码的问题,但 JDK 对日历常量使用了一些意外的值。例如,月份以零开头。换句话说,Calendar.JANUARY 为 0。另一方面,工作日为 1 到 7,从星期日开始为 1。等等。

I don't know if this is an issue with your code, but JDK uses some unexpected values for Calendar constants. For example, months star with zero. In other words, Calendar.JANUARY is 0. On the other hand, weekdays are 1 to 7, starting with Sunday as 1. etc.

暮年慕年 2024-09-09 23:02:09

幸运的是,我对 Java 中的 Date 了解不多,但我知道它基本上是一个困难且糟糕的 API。继续使用 JodaTime,直到新的 JSR-310 完成。

I luckily don't know much about Date in Java, but I know it's basically a difficult and bad API. Go for JodaTime until the new JSR-310 is done.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文