【问题标题】:How to get the day of the week using enumeration [closed]如何使用枚举获取星期几[关闭]
【发布时间】:2021-03-18 11:57:33
【问题描述】:

我已经有了代码,但星期几不匹配。 第二个输入有点偏离。我认为这是朱利安日公式。

enum Day {
 MON, TUE, WED, THU, FRI, SAT, SUN;
}
  public Day dayOfTheWeek() {
  
  int D = day, M = month, Y = year, A, B, C, intindex;
  
  double E = 0, F = 0, JD = 0, num1, num2;
  
  if((M == 1 || M == 2)) {
    Y--;
    M += 12;
  }
  
  A = Y / 100;
  B = A / 4;
  C = 2 - A + B;
  E = 365.25 * (Y + 4716);
  F = 30.6001 * (M + 1);
  JD = (C + D + E + F) - 1524.5;
  num1 = JD % 7;
  intindex = (int) num1;
  num2 = num1 - intindex;
  
  if(num2 + 0.1 >= 1) {
    intindex++;
  }
  
  return Day.values()[intindex];
  
  }

输入:

1/1/1972
20/8/1980

输出:

1/1/1972
SAT
20/8/1980
TUE

预期输出:

1/1/1972
SAT
20/8/1980
WED

编辑:代码现在可以正常工作了。只需要从 MON 到 SUN 而不是 SUN 到 MON 的枚举 Day。

【问题讨论】:

  • 不,我想他也在 codechum 学习,我用来学习封装@fluffy
  • 您应该在发布家庭作业/学习而不是实际解决方案时提及。
  • 对不起,我下次再做。感谢您推荐@Basil Bourque

标签: java date datetime-format encapsulation dayofweek


【解决方案1】:

我建议您使用modern date-time API

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

public class Main {
    public static void main(String[] args) {
        // Test
        DayOfWeek dayOfWeek = getDay("1/1/1972");
        System.out.println(dayOfWeek);
        System.out.println(dayOfWeek.getDisplayName(TextStyle.FULL, Locale.ENGLISH));
        System.out.println(dayOfWeek.getDisplayName(TextStyle.SHORT, Locale.ENGLISH));
    }

    static DayOfWeek getDay(String dateString) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d/M/uuuu");
        LocalDate date = LocalDate.parse(dateString, dtf);
        return date.getDayOfWeek();
    }
}

输出:

SATURDAY
Saturday
Sat

通过 Trail: Date Time 了解有关现代日期时间 API 的更多信息。

【讨论】:

  • 我怀疑这个问题是编程作业,而不是实际问题。
【解决方案2】:

我明白了。只需要将枚举从 MON 到 SUN 而不是从 SUN 到 MON。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-19
    • 2014-10-21
    • 2014-11-12
    相关资源
    最近更新 更多