如何通过特定日期确定星期几?

时间:2011-03-11 07:44:24

标签: java date

例如我有日期:“2010年2月23日”(2010年2月23日)。我想将它传递给一个能够返回星期几的函数。我怎么能这样做?

在此示例中,函数应返回String“Tue”。

此外,如果只需要日序,那么如何检索?

25 个答案:

答案 0 :(得分:305)

是。视具体情况而定:

  • 您可以使用java.util.Calendar

    Calendar c = Calendar.getInstance();
    c.setTime(yourDate);
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    
  • 如果您需要输出为Tue而不是3(星期几从1开始编制索引),而不是通过日历,只需重新格式化字符串:new SimpleDateFormat("EE").format(date)EE表示“星期几,短版”)

  • 如果您将输入作为字符串而不是Date,则应使用SimpleDateFormat对其进行解析:new SimpleDateFormat("dd/M/yyyy").parse(dateString)

  • 您可以使用joda-time的DateTime并致电dateTime.dayOfWeek()和/或DateTimeFormat

答案 1 :(得分:55)

  String input_date="01/08/2012";
  SimpleDateFormat format1=new SimpleDateFormat("dd/MM/yyyy");
  Date dt1=format1.parse(input_date);
  DateFormat format2=new SimpleDateFormat("EEEE"); 
  String finalDay=format2.format(dt1);

使用此代码从输入日期查找日期名称。简单且经过充分测试。

答案 2 :(得分:25)

只需使用SimpleDateFormat

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", java.util.Locale.ENGLISH);
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("EEE, d MMM yyyy");
String sMyDate = sdf.format(myDate);

结果是: 2013年12月28日星期六

默认构造函数采用“默认”Locale,因此在需要特定模式时请小心使用它。

public SimpleDateFormat(String pattern) {
    this(pattern, Locale.getDefault(Locale.Category.FORMAT));
}

答案 3 :(得分:19)

TL;博士

使用java.time ...

LocalDate.parse(                               // Generate `LocalDate` object from String input.
             "23/2/2010" ,
             DateTimeFormatter.ofPattern( "d/M/uuuu" ) 
         )                                    
         .getDayOfWeek()                       // Get `DayOfWeek` enum object.
         .getDisplayName(                      // Localize. Generate a String to represent this day-of-week.
             TextStyle.SHORT_STANDALONE ,      // How long or abbreviated. Some languages have an alternate spelling for "standalone" use (not so in English).
             Locale.US                         // Or Locale.CANADA_FRENCH and such. Specify a `Locale` to determine (1) human language for translation, and (2) cultural norms for abbreviation, punctuation, etc.
         ) 
  

周二

请参阅此code run live at IdeOne.com(但只有Locale.US在那里工作)。

java.time

请参阅上面的示例代码,并查看correct Answer for java.time by Przemek

序号

  

如果只需要日序,那该怎么办?

对于序号,请考虑传递DayOfWeek枚举对象,例如DayOfWeek.TUESDAY。请记住,DayOfWeek是一个智能对象,而不仅仅是字符串或纯粹的整数。 Using those enum objects使您的代码更加自我记录,确保有效值,并提供type-safety

但如果你坚持,ask DayOfWeek for a number。根据{{​​3}}标准,您可以在周一至周日获得1-7。

int ordinal = myLocalDate.getDayOfWeek().getValue() ;

约达时间

更新: Joda-Time项目现在处于维护模式。该团队建议迁移到java.time类。 java.time框架内置于Java 8(以及ISO 8601back-ported to Java 6 & 7)中。

以下是使用further adapted to Android库版本2.4的示例代码,如Joda-Time中所述。 Joda-Time远远优于与Java捆绑的java.util.Date/.Calendar类。

LocalDate

Joda-Time提供accepted answer by Bozho类来表示仅限日期,没有任何时间或时区。正是这个问题所要求的。与Java捆绑在一起的旧java.util.Date/.Calendar类缺乏这个概念。

解析

将字符串解析为日期值。

String input = "23/2/2010";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( input );

提取

从日期值中提取周数和名称的日期。

int dayOfWeek = localDate.getDayOfWeek(); // Follows ISO 8601 standard, where Monday = 1, Sunday = 7.
Locale locale = Locale.US;  // Locale specifies the human language to use in determining day-of-week name (Tuesday in English versus Mardi in French).
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "E" ).withLocale( locale );
String output = formatterOutput.print( localDate ); // 'E' is code for abbreviation of day-of-week name. See Joda-Time doc.
String outputQuébécois = formatterOutput.withLocale( Locale.CANADA_FRENCH ).print( localDate );

转储

转储到控制台。

System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate ); // Defaults to ISO 8601 formatted strings.
System.out.println( "dayOfWeek: " + dayOfWeek );
System.out.println( "output: " + output );
System.out.println( "outputQuébécois: " + outputQuébécois );

运行

跑步时。

input: 23/2/2010
localDate: 2010-02-23
dayOfWeek: 2
output: Tue
outputQuébécois: mar.

关于java.time

LocalDate框架内置于Java 8及更高版本中。这些类取代了麻烦的旧java.time日期时间类,例如legacyjava.util.Date和& Calendar

现在位于SimpleDateFormatJoda-Time项目建议迁移到maintenance mode类。

要了解详情,请参阅java.time。并搜索Stack Overflow以获取许多示例和解释。规范是Oracle Tutorial

从哪里获取java.time类?

How to use ThreeTenABP…项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如ThreeTen-ExtraIntervalYearWeekYearQuarter

答案 4 :(得分:12)

对于 Java 8或更高版本,首选 Localdate

import java.time.LocalDate;

public static String findDay(int month, int day, int year) {

    LocalDate localDate = LocalDate.of(year, month, day);

    java.time.DayOfWeek dayOfWeek = localDate.getDayOfWeek();
    System.out.println(dayOfWeek);

    return dayOfWeek.toString();
}

注意::如果输入是字符串/用户定义的,则应将其解析为 int

答案 5 :(得分:11)

java.time

使用Java 8及更高版本中内置的java.time框架。

DayOfWeek enum可以生成当天名称的字符串,该字符串自动定位为Locale的人类语言和文化规范。指定TextStyle表示您需要长格式或缩写名称。

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.format.TextStyle
import java.util.Locale
import java.time.DayOfWeek;

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yyyy");
LocalDate date = LocalDate.parse("23/2/2010", formatter); // LocalDate = 2010-02-23
DayOfWeek dow = date.getDayOfWeek();  // Extracts a `DayOfWeek` enum object.
String output = dow.getDisplayName(TextStyle.SHORT, Locale.US); // String = Tue

答案 6 :(得分:7)

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

答案 7 :(得分:6)

您可以尝试以下代码:

import java.time.*;

public class Test{
   public static void main(String[] args) {
      DayOfWeek dow = LocalDate.of(2010,Month.FEBRUARY,23).getDayOfWeek();
      String s = String.valueOf(dow);
      System.out.println(String.format("%.3s",s));
   }
}

答案 8 :(得分:5)

另一种“有趣”的方式是使用Doomsday algorithm。这是一种更长的方法,但如果您不需要创建具有给定日期的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;
    }
}

答案 9 :(得分:4)

...
import java.time.LocalDate;
...
//String month = in.next();
int mm = in.nextInt();
//String day = in.next();
int dd = in.nextInt();
//String year = in.next();
int yy = in.nextInt();
in.close();
LocalDate dt = LocalDate.of(yy, mm, dd);
System.out.print(dt.getDayOfWeek());

答案 10 :(得分:3)

private String getDay(Date date){

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
    //System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());                       
    return simpleDateFormat.format(date).toUpperCase();
}

private String getDay(String dateStr){
    //dateStr must be in DD-MM-YYYY Formate
    Date date = null;
    String day=null;

    try {
        date = new SimpleDateFormat("DD-MM-YYYY").parse(dateStr);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
        //System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
        day = simpleDateFormat.format(date).toUpperCase();


    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    return day;
}

答案 11 :(得分:3)

一行答案:

return LocalDate.parse("06/02/2018",DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();

用法示例:

public static String getDayOfWeek(String date){
  return LocalDate.parse(date, DateTimeFormatter.ofPattern("dd/MM/yyyy")).getDayOfWeek().name();
}

public static void callerMethod(){
   System.out.println(getDayOfWeek("06/02/2018")); //TUESDAY
}

答案 12 :(得分:3)

可以使用以下代码段作为输入,例如(day =&#34; 08&#34;,month =&#34; 05&#34;,year =&#34; 2015&#34;输出将为& #34;星期三&#34)

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();

答案 13 :(得分:2)

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

答案 14 :(得分:1)

<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" ...>
  <property name="net.sf.jasperreports.export.xls.detect.cell.type" value="true"/>

答案 15 :(得分:1)

Calendar cal = Calendar.getInstance(desired date);
cal.setTimeInMillis(System.currentTimeMillis());
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

通过提供当前时间戳来获取日期值。

答案 16 :(得分:1)

添加另一种完全符合OP要求的方式,而无需使用最新的内置方法:

public static String getDay(String inputDate) {
    String dayOfWeek = null;
    String[] days = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};

    try {
        SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
        Date dt1 = format1.parse(inputDate);
        dayOfWeek = days[dt1.getDay() - 1];
    } catch(Exception e) {
        System.out.println(e);
    }

    return dayOfWeek;
}

答案 17 :(得分:1)

hackerrank Java Date and Time

面临挑战

我个人更喜欢LocalDate类。

  1. 导入java.time.LocalDate
  2. 使用“ of”方法检索localDate,该方法在其中使用3个参数 “ int”格式。
  3. 最后,使用“ getDayOfWeek”方法获取当天的名称。

有一个关于这一挑战的视频。

Java Date and Time Hackerrank solution

我希望它会有所帮助:)

答案 18 :(得分:0)

您可以使用以下方法通过传递特定日期

来获取星期几

这里对于Calendar类的set方法,Tricky part是月参数的索引,从0开始

public static String getDay(int day, int month, int year) {

        Calendar cal = Calendar.getInstance();

        if(month==1){
            cal.set(year,0,day);
        }else{
            cal.set(year,month-1,day);
        }

        int dow = cal.get(Calendar.DAY_OF_WEEK);

        switch (dow) {
        case 1:
            return "SUNDAY";
        case 2:
            return "MONDAY";
        case 3:
            return "TUESDAY";
        case 4:
            return "WEDNESDAY";
        case 5:
            return "THURSDAY";
        case 6:
            return "FRIDAY";
        case 7:
            return "SATURDAY";
        default:
            System.out.println("GO To Hell....");
        }

        return null;
    }

答案 19 :(得分:0)

使用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));
    }
}

答案 20 :(得分:0)

Calendar类具有内置displayName功能:

Calendar.getInstance().getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); // Thu   

Calendar.SHORT -> Thu
Calendar.LONG_FORMAT -> Thursday

自Java 1.6起可用。另请参阅Oracle documentation

答案 21 :(得分:0)

//to get day of any date

import java.util.Scanner; 
import java.util.Calendar; 
import java.util.Date;

public class Show {

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


            String input_date = month+"/"+day+"/"+year;

            Date now = new Date(input_date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            int final_day = (calendar.get(Calendar.DAY_OF_WEEK));

            String finalDay[]={"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"};

            System.out.println(finalDay[final_day-1]);

    }

    public static void main(String[] args) { 
            Scanner in = new Scanner(System.in); 
            String month = in.next(); 
        String day = in.next();
            String year = in.next();

            getDay(day, month, year);
    }

}

答案 22 :(得分:0)

这正常工作...

    There was an error saving the HTTPS developer certificate to the current user personal certificate store.

它提供了内置方法getDayOfWeek()来获取特定星期几:

java.time.LocalDate; //package related to time and date

要将枚举int t; Scanner s = new Scanner(System.in); t = s.nextInt(); s.nextLine(); while(t-->0) { int d, m, y; String ss = s.nextLine(); String []sss = ss.split(" "); d=Integer.parseInt(sss[0]); m = Integer.parseInt(sss[1]); y = Integer.parseInt(sss[2]); LocalDate l = LocalDate.of(y, m, d); //method to get the localdate instance System.out.println(l.getDayOfWeek()); //this returns the enum DayOfWeek 的值分配给字符串,您可以使用名为l.getDayOfWeek()的枚举方法来返回枚举对象的值。

答案 23 :(得分:0)

下面的方法检索了7天并在Kotlin的List Array中返回了几天的短名称,您可以将其重新格式化然后以Java格式表示,只是表示Calendar如何返回短名

private fun getDayDisplayName():List<String>{
        val calendar = Calendar.getInstance()
        val dates= mutableListOf<String>()
        dates.clear()
        val s=   calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US)
        dates.add(s)
        for(i in 0..5){
            calendar.roll( Calendar.DATE, -1)
            dates.add(calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US))
        }
        return dates.toList()
    }

输出结果类似

I/System.out: Wed
    Tue
    Mon
    Sun
I/System.out: Sat
    Fri
    Thu

答案 24 :(得分:-3)

下面是使用Java 1.8 Time API的两行代码段。

LocalDate localDate = LocalDate.of(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day));
String dayOfWeek = String.valueOf(localDate.getDayOfWeek());