java - 按年、月、日查找日期的名称

标签 java

如果我在 Java 中有 int year、int month、int day,如何找到日期的名称?是否已经有一些功能?

最佳答案

使用 SimpleDateFormat使用 EEEE 模式来获取星期几的名称。

// Assuming that you already have this.
int year = 2011;
int month = 7;
int day = 22;

// First convert to Date. This is one of the many ways.
String dateString = String.format("%d-%d-%d", year, month, day);
Date date = new SimpleDateFormat("yyyy-M-d").parse(dateString);

// Then get the day of week from the Date based on specific locale.
String dayOfWeek = new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);

System.out.println(dayOfWeek); // Friday

在这里,它被包装成一个漂亮的 Java 类。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


public class DateUtility
{

    public static void main(String args[]){
        System.out.println(dayName("2015-03-05 00:00:00", "YYYY-MM-DD HH:MM:ss"));
    }

    public static String dayName(String inputDate, String format){
        Date date = null;
        try {
            date = new SimpleDateFormat(format).parse(inputDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new SimpleDateFormat("EEEE", Locale.ENGLISH).format(date);
    }
}

关于java - 按年、月、日查找日期的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6789437/

相关文章:

java - 如何从另一台计算机的外部 .jar 获取类?

java - 管理全局对象或列表

java - 如何防止代币替换攻击?

java - 我需要一些方法将 BigInt 转换为 Bytes 数组,就像 java 中的 swift 一样

java - 将抽象方法从父类(super class)扩展到子类

java - 如何将 Fop 配置文件加载到 FopFactory

java - 使用For循环获取素数java

java - 如何选择元素进行 react 选择 Selenium 模式

java - 读取输入字符串

java - 将类枚举传递给克隆是否克隆安全?