java - 如何使用枚举获取星期几
问题描述
我已经有了代码,但星期几不匹配。第二个输入有点偏离。我认为这是朱利安日公式。
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。
解决方案
我建议您使用现代日期时间 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 的更多信息。
推荐阅读
- javascript - 在数组数组上使用 math.random 的问题
- highcharts - Highcharts 组织结构图的拖放功能
- python - 从 json 文件中提取 URL
- javascript - 如何比较两个对象数组并删除 JavaScript 中的重复项?
- javascript - 如何在我的网站上的光标上制作十字准线效果
- azure-devops - 无法将工件从一个阶段复制到 Azure 管道中的另一个阶段
- java - Eclipse 使用 Maven 更改项目的版本?
- google-sheets - GoogleFinance 在获取股票报价时经常返回#N/A 和内部错误消息
- r - 根据其他列在data.frame中添加一个新列
- vba - 如何自动点击超链接