如果我在 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/