2017-10-29 302 views
0

我在hackerrank.com上做了一个简单的例子,要求我们返回给定日期的那一天。例如:如果日期为2015年5月8日(月日),则应返回星期三。查找给定日期的星期几

这是我写的这个任务

public static String getDay(String day, String month, String year) { 
    String[] dates=new String[]{"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"}; 
    Calendar cal=Calendar.getInstance(); 
    cal.set(Integer.valueOf(year),Integer.valueOf(month),Integer.valueOf(day)); 
    int date_of_week=cal.get(Calendar.DAY_OF_WEEK); 
    return dates[date_of_week-1]; 
} 

我的代码返回“星期六”为给定的例子应该是“星期三”的代码。对于当前日期为2017年10月29日,则返回“星期三”。 任何人都可以请帮我解决这个问题?

+2

你是否真的必须使用'Calendar'而不是更现代的'java.time' API? 'LocalDate'比这个好得多。 (另外,按照日/月/年的顺序接受参数感觉很奇怪,而不是年/月/日;为什么接受它们是字符串而不是整数?如果调用代码只有字符串,它可以执行解析本身) –

+0

@JonSkeet是的,我试了LocalDate。它比使用日历更好。 –

回答

4

假设你正在使用Java 8+,你可以使用LocalDate和类似

public static String getDay(String day, String month, String year) { 
    return LocalDate.of(
      Integer.parseInt(year), 
      Integer.parseInt(month), 
      Integer.parseInt(day) 
    ).getDayOfWeek().toString(); 
} 

另外请注意,您所描述的方法,采取monthdayyear但你实现它采取daymonthyear(确保你调用的是正确的)。我测试了上面

public static void main(String[] args) throws Exception { 
    System.out.println(getDay("05", "08", "2015")); 
    System.out.println(getDay("29", "10", "2017")); 
} 

我也得到(预期)

WEDNESDAY 
SUNDAY 

如果你不能使用Java 8(或只是为了解决当前解决方案),Calendar需要month从偏移1Calendar#JANUARY0)。所以,你需要(和喜欢parseIntvalueOf,第一返回原始的 - 第二的Integer实例)类似

public static String getDay(String day, String month, String year) { 
    String[] dates = new String[] { "SUNDAY", "MONDAY", "TUESDAY", // 
      "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY" }; 
    Calendar cal = Calendar.getInstance(); 
    cal.set(Integer.parseInt(year), // 
      Integer.parseInt(month) - 1, // <-- add -1 
      Integer.parseInt(day)); 
    int date_of_week = cal.get(Calendar.DAY_OF_WEEK); 
    return dates[date_of_week - 1]; 
} 

这给上述同样的结果。

+1

最后一部分是不正确的。查看今年打印的是哪一年 - > https://ideone.com/8N5UQJ。 “从1900开始的偏移量”部分用于java.util.Date(int年,int月,int日期)' – Vasan

+0

@Vasan Wow。固定。谢谢。 –

+0

@ElliottFrisch它的工作。我在'month'参数中加了-1。非常感谢。 –

2

Calendar的月份为零,基于cal.set(int,int,int)。如果我打电话给getDay("29", "9", "2017"),它将返回星期日。因此,请用较少的一个月(即9)致电您的方法,或者在月份的日历常数(Calendar.OCTOBER)中调用它,或在致电cal.set时执行month+1

看到这个运行演示:https://ideone.com/A6WGRJ。我还添加了打印日期以确认它打印正确的日期。

+2

@ElliottFrisch我相信你在考虑'java.util.Date'。 – Vasan

+0

是的,我在月份中加了-1。现在它工作正常。谢谢。 –