首页 > 解决方案 > 如何使用枚举获取星期几

问题描述

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

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

编辑:代码现在工作正常。只需要将枚举 Day 从 MON 设为 SUN 而不是从 SUN 到 MON。

标签: javadatedatetime-formatencapsulationdayofweek

解决方案


我建议您使用现代日期时间 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 的更多信息。


推荐阅读