java - 通过数字获取当天的名称

标签 java formula

这可能是一个非常独特的问题,因为我在 Google 上搜索了一段时间,但找不到解决方案。这也很有趣。

我需要bascailly的是一个数字,你可以通过它得到日期名称。

例如我们的号码是 7,我们需要通过一个公式来找出它的日期名称,但是对于 7 来说它是基本的,您只需在 switch 语句中获取“星期六”即可。

基本上获取名字很简单,你就搞定了:

switch (dayNumber) {
    case 1: return "Sunday"; etc...

但我认为我的问题很复杂,我不确定逻辑上是否有可能的解决方案。

我想通过数字获取一周的索引号。

例子:

  • 第 7 天 - 指数:7
  • 第 16 天 - 索引:2(因为您计算前 2 周 7 + 7 = 14,然后 + 2 = 16,所以这一天是星期一。
  • 第 24 天 - 指数:3

为什么我需要这个:

我最近在 Java 类(class)中遇到了一个问题,与此无关,但它与循环月份日期有关,所以我想发挥创意甚至获得特定日期的名称,在使用数学函数和公式的快速方法。

关于如何获取名称的示例:

for (int i = 1; i <= 31; i++) {
    System.out.println(getDayByInteger(i));
}

public static String getDayByInteger(int day) {
        int dayNumber = 0; //TODO Formula..
        switch (dayNumber) {
            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: return "N/A";
        }
    }

我不介意它是否仅支持 1-31 的数字范围,但我的问题集中在是否有可能使其适用于任何数字,因为您始终可以构建适用于特定数字范围的公式我想。

甚至可能是任何数字吗?还是需要检查报表?

最佳答案

您只需使用模数并编辑您的案例:

    switch (dayNumber%7) {
        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 0:                     //change case 7 to case 0
            return "Saturday";
        default: return "N/A";
    }

关于java - 通过数字获取当天的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21112050/

相关文章:

java - 数据库的多线程问题

java - 不使用 XPath 从 webtable 内的元素获取文本(Selenium Web 驱动程序 + Java)

如果数字的主要影响来自函数,R 不会忽略与数字交互的基本水平

r - 避免在拟合多个线性回归模型时重复编写模型公式

java - 火力地堡数据库 : Getting "No-Argument Constructor" Error Despite Having It

java - 数据绑定(bind)在对话框中不起作用 - 为什么?

java - 由(一对一): org. hibernate.AnnotationException 引发 Hibernate:未知的mappedBy in:引用的属性未知:

arrays - 使用索引匹配的数组公式

string - Excel空字符串公式

formula - (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2 的证明是什么