例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?

在这个例子中,函数应该返回String "Tue"。

此外,如果只需要日期顺序,如何检索?


当前回答

可以使用以下代码片段进行输入,如(day = "08", month = "05", year = "2015",输出将是"WEDNESDAY")

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
calendar.set(Calendar.MONTH, (Integer.parseInt(month)-1));
calendar.set(Calendar.YEAR, Integer.parseInt(year));
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();

其他回答

下面是两行代码片段,使用Java 1.8 Time API满足您的需求。

LocalDate localDate = LocalDate.of(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day));
String dayOfWeek = String.valueOf(localDate.getDayOfWeek());
public class TryDateFormats {
    public static void main(String[] args) throws ParseException {
        String month = "08";
        String day = "05";
        String year = "2015";
        String inputDateStr = String.format("%s/%s/%s", day, month, year);
        Date inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);
        String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
        System.out.println(dayOfWeek);
    }
}

通过使用java.util.scanner包给用户输入日期、月和年来查找星期几的程序:

import java.util.Scanner;

public class Calender {
    public static String getDay(String day, String month, String year) {

        int ym, yp, d, ay, a = 0;
        int by = 20;
        int[] y = new int[]{6, 4, 2, 0};
        int[] m = new int []{0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5};

        String[] wd = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

        int gd = Integer.parseInt(day);
        int gm = Integer.parseInt(month);
        int gy = Integer.parseInt(year);

        ym = gy % 100;
        yp = ym / 4;
        ay = gy / 100;

        while (ay != by) {
            by = by + 1;
            a = a + 1;

            if(a == 4) {
                a = 0;
            }
        }

        if ((ym % 4 == 0) && (gm == 2)) {
            d = (gd + m[gm - 1] + ym + yp + y[a] - 1) % 7;
        } else
            d = (gd + m[gm - 1] + ym + yp + y[a]) % 7;

        return wd[d];
    }

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        String day = in.next();
        String month = in.next();
        String year = in.next();

        System.out.println(getDay(day, month, year));
    }
}

另一个“有趣”的方法是使用末日算法。这是一个更长的方法,但如果您不需要用给定的日期创建Calendar对象,那么它也更快。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 *
 * @author alain.janinmanificat
 */
public class Doomsday {

    public static HashMap<Integer, ArrayList<Integer>> anchorDaysMap = new HashMap<>();
    public static HashMap<Integer, Integer> doomsdayDate = new HashMap<>();
    public static String weekdays[] = new DateFormatSymbols(Locale.FRENCH).getWeekdays();

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws ParseException, ParseException {

        // Map is fed manually but we can use this to calculate it : http://en.wikipedia.org/wiki/Doomsday_rule#Finding_a_century.27s_anchor_day
        anchorDaysMap.put(Integer.valueOf(0), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1700));
                add(Integer.valueOf(2100));
                add(Integer.valueOf(2500));
            }
        });

        anchorDaysMap.put(Integer.valueOf(2), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1600));
                add(Integer.valueOf(2000));
                add(Integer.valueOf(2400));
            }
        });

        anchorDaysMap.put(Integer.valueOf(3), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1500));
                add(Integer.valueOf(1900));
                add(Integer.valueOf(2300));
            }
        });

        anchorDaysMap.put(Integer.valueOf(5), new ArrayList<Integer>() {
            {
                add(Integer.valueOf(1800));
                add(Integer.valueOf(2200));
                add(Integer.valueOf(2600));
            }
        });

        //Some reference date that always land on Doomsday
        doomsdayDate.put(Integer.valueOf(1), Integer.valueOf(3));
        doomsdayDate.put(Integer.valueOf(2), Integer.valueOf(14));
        doomsdayDate.put(Integer.valueOf(3), Integer.valueOf(14));
        doomsdayDate.put(Integer.valueOf(4), Integer.valueOf(4));
        doomsdayDate.put(Integer.valueOf(5), Integer.valueOf(9));
        doomsdayDate.put(Integer.valueOf(6), Integer.valueOf(6));
        doomsdayDate.put(Integer.valueOf(7), Integer.valueOf(4));
        doomsdayDate.put(Integer.valueOf(8), Integer.valueOf(8));
        doomsdayDate.put(Integer.valueOf(9), Integer.valueOf(5));
        doomsdayDate.put(Integer.valueOf(10), Integer.valueOf(10));
        doomsdayDate.put(Integer.valueOf(11), Integer.valueOf(7));
        doomsdayDate.put(Integer.valueOf(12), Integer.valueOf(12));

        long time = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {

            //Get a random date
            int year = 1583 + new Random().nextInt(500);
            int month = 1 + new Random().nextInt(12);
            int day = 1 + new Random().nextInt(7);

            //Get anchor day and DoomsDay for current date
            int twoDigitsYear = (year % 100);
            int century = year - twoDigitsYear;
            int adForCentury = getADCentury(century);
            int dd = ((int) twoDigitsYear / 12) + twoDigitsYear % 12 + (int) ((twoDigitsYear % 12) / 4);

            //Get the gap between current date and a reference DoomsDay date
            int referenceDay = doomsdayDate.get(month);
            int gap = (day - referenceDay) % 7;

            int result = (gap + adForCentury + dd) % 7;

            if(result<0){
                result*=-1;
            }
            String dayDate= weekdays[(result + 1) % 8];
            //System.out.println("day:" + dayDate);
        }
        System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 80

         time = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            Calendar c = Calendar.getInstance();
            //I should have used random date here too, but it's already slower this way
            c.setTime(new SimpleDateFormat("dd/MM/yyyy").parse("12/04/1861"));
//            System.out.println(new SimpleDateFormat("EE").format(c.getTime()));
            int result2 = c.get(Calendar.DAY_OF_WEEK);
//            System.out.println("day idx :"+ result2);
        }
        System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 884
    }

    public static int getADCentury(int century) {
        for (Map.Entry<Integer, ArrayList<Integer>> entry : anchorDaysMap.entrySet()) {
            if (entry.getValue().contains(Integer.valueOf(century))) {
                return entry.getKey();
            }
        }
        return 0;
    }
}
import java.text.SimpleDateFormat;
import java.util.Scanner;

class DayFromDate {

    public static void main(String args[]) {

        System.out.println("Enter the date(dd/mm/yyyy):");
        Scanner scan = new Scanner(System.in);
        String Date = scan.nextLine();

        try {
            boolean dateValid = dateValidate(Date);

            if(dateValid == true) {
                SimpleDateFormat df = new SimpleDateFormat( "dd/MM/yy" );  
                java.util.Date date = df.parse( Date );   
                df.applyPattern( "EEE" );  
                String day= df.format( date ); 

                if(day.compareTo("Sat") == 0 || day.compareTo("Sun") == 0) {
                    System.out.println(day + ": Weekend");
                } else {
                    System.out.println(day + ": Weekday");
                }
            } else {
                System.out.println("Invalid Date!!!");
            }
        } catch(Exception e) {
            System.out.println("Invalid Date Formats!!!");
        }
     }

    static public boolean dateValidate(String d) {

        String dateArray[] = d.split("/");
        int day = Integer.parseInt(dateArray[0]);
        int month = Integer.parseInt(dateArray[1]);
        int year = Integer.parseInt(dateArray[2]);
        System.out.print(day + "\n" + month + "\n" + year + "\n");
        boolean leapYear = false;

        if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
            leapYear = true;
        }

        if(year > 2099 || year < 1900)
            return false;

        if(month < 13) {
            if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                if(day > 31)
                    return false;
            } else if(month == 4 || month == 6 || month == 9 || month == 11) {
                if(day > 30)
                    return false;
            } else if(leapYear == true && month == 2) {
                if(day > 29)
                    return false;
            } else if(leapYear == false && month == 2) {
                if(day > 28)
                    return false;
            }

            return true;    
        } else return false;
    }
}