例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
当前回答
简单地使用SimpleDateFormat。
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", java.util.Locale.ENGLISH);
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("EEE, d MMM yyyy");
String sMyDate = sdf.format(myDate);
结果是:2013年12月28日星期六
默认构造函数接受“默认”区域设置,因此在需要特定模式时要小心使用它。
public SimpleDateFormat(String pattern) {
this(pattern, Locale.getDefault(Locale.Category.FORMAT));
}
其他回答
是的。根据具体情况:
You can use java.util.Calendar: Calendar c = Calendar.getInstance(); c.setTime(yourDate); int dayOfWeek = c.get(Calendar.DAY_OF_WEEK); if you need the output to be Tue rather than 3 (Days of week are indexed starting at 1 for Sunday, see Calendar.SUNDAY), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version") if you have your input as string, rather than Date, you should use SimpleDateFormat to parse it: new SimpleDateFormat("dd/M/yyyy").parse(dateString) you can use joda-time's DateTime and call dateTime.dayOfWeek() and/or DateTimeFormat. edit: since Java 8 you can now use java.time package instead of joda-time
import java.text.SimpleDateFormat;
import java.util.Scanner;
class DayFromDate {
public static void main(String args[]) {
System.out.println("Enter the date(dd/mm/yyyy):");
Scanner scan = new Scanner(System.in);
String Date = scan.nextLine();
try {
boolean dateValid = dateValidate(Date);
if(dateValid == true) {
SimpleDateFormat df = new SimpleDateFormat( "dd/MM/yy" );
java.util.Date date = df.parse( Date );
df.applyPattern( "EEE" );
String day= df.format( date );
if(day.compareTo("Sat") == 0 || day.compareTo("Sun") == 0) {
System.out.println(day + ": Weekend");
} else {
System.out.println(day + ": Weekday");
}
} else {
System.out.println("Invalid Date!!!");
}
} catch(Exception e) {
System.out.println("Invalid Date Formats!!!");
}
}
static public boolean dateValidate(String d) {
String dateArray[] = d.split("/");
int day = Integer.parseInt(dateArray[0]);
int month = Integer.parseInt(dateArray[1]);
int year = Integer.parseInt(dateArray[2]);
System.out.print(day + "\n" + month + "\n" + year + "\n");
boolean leapYear = false;
if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
leapYear = true;
}
if(year > 2099 || year < 1900)
return false;
if(month < 13) {
if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
if(day > 31)
return false;
} else if(month == 4 || month == 6 || month == 9 || month == 11) {
if(day > 30)
return false;
} else if(leapYear == true && month == 2) {
if(day > 29)
return false;
} else if(leapYear == false && month == 2) {
if(day > 28)
return false;
}
return true;
} else return false;
}
}
方法下面检索七天,并返回短名称的天在列表数组在Kotlin,你可以重新格式化然后在Java格式,只是提出想法日历可以返回短名称
private fun getDayDisplayName():List<String>{
val calendar = Calendar.getInstance()
val dates= mutableListOf<String>()
dates.clear()
val s= calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US)
dates.add(s)
for(i in 0..5){
calendar.roll( Calendar.DATE, -1)
dates.add(calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US))
}
return dates.toList()
}
结果是这样的
I/System.out: Wed
Tue
Mon
Sun
I/System.out: Sat
Fri
Thu
LocalDate date=LocalDate.now();
System.out.println(date.getDayOfWeek());//prints THURSDAY
System.out.println(date.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US) ); //prints Thu
java.time.DayOfWeek is a enum which returns the singleton instance for the day-of-week of the weekday of the date.
博士tl;
使用java.time…
LocalDate.parse( // Generate `LocalDate` object from String input.
"23/2/2010" ,
DateTimeFormatter.ofPattern( "d/M/uuuu" )
)
.getDayOfWeek() // Get `DayOfWeek` enum object.
.getDisplayName( // Localize. Generate a String to represent this day-of-week.
TextStyle.SHORT_STANDALONE , // How long or abbreviated. Some languages have an alternate spelling for "standalone" use (not so in English).
Locale.US // Or Locale.CANADA_FRENCH and such. Specify a `Locale` to determine (1) human language for translation, and (2) cultural norms for abbreviation, punctuation, etc.
)
你
这段代码在IdeOne.com上实时运行(但仅限于区域设置。美国在那里工作)。
java.time
请参阅上面的示例代码,并查看java的正确答案。时间由Przemek。
序数
如果只需要按日期排序,如何才能取回?
对于序数,可以考虑传递DayOfWeek枚举对象,例如DayOfWeek. tuesday。请记住,DayOfWeek是一个智能对象,而不仅仅是一个字符串或整数。使用这些枚举对象可以使您的代码更具自文档性,确保有效值,并提供类型安全。
但如果你坚持,可以问DayOfWeek要一个数字。根据ISO 8601标准,周一到周日有1-7个。
int ordinal = myLocalDate.getDayOfWeek().getValue() ;
乔达时间
更新:Joda-Time项目现在处于维护模式。团队建议迁移到java。时间类。java。时间框架内置于Java 8(以及向后移植到Java 6和7,并进一步适应Android)。
下面是使用Joda-Time库版本2.4的示例代码,正如Bozho在接受的回答中提到的那样。Joda-Time远优于java.util.Date/。与Java绑定的日历类。
LocalDate
Joda-Time提供了LocalDate类来表示只有日期,没有任何时间或时区。这正是这个问题所需要的。旧的java.util.Date/。与Java绑定的日历类缺乏这个概念。
解析
将字符串解析为日期值。
String input = "23/2/2010";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d/M/yyyy" );
LocalDate localDate = formatter.parseLocalDate( input );
提取
从日期值中提取星期数和名称。
int dayOfWeek = localDate.getDayOfWeek(); // Follows ISO 8601 standard, where Monday = 1, Sunday = 7.
Locale locale = Locale.US; // Locale specifies the human language to use in determining day-of-week name (Tuesday in English versus Mardi in French).
DateTimeFormatter formatterOutput = DateTimeFormat.forPattern( "E" ).withLocale( locale );
String output = formatterOutput.print( localDate ); // 'E' is code for abbreviation of day-of-week name. See Joda-Time doc.
String outputQuébécois = formatterOutput.withLocale( Locale.CANADA_FRENCH ).print( localDate );
Dump
转储到控制台。
System.out.println( "input: " + input );
System.out.println( "localDate: " + localDate ); // Defaults to ISO 8601 formatted strings.
System.out.println( "dayOfWeek: " + dayOfWeek );
System.out.println( "output: " + output );
System.out.println( "outputQuébécois: " + outputQuébécois );
Run
运行时。
input: 23/2/2010
localDate: 2010-02-23
dayOfWeek: 2
output: Tue
outputQuébécois: mar.
关于java.time
java。时间框架内置于Java 8及更高版本中。这些类取代了麻烦的旧遗留日期-时间类,如java.util。日期,日历和简单日期格式。
Joda-Time项目现在处于维护模式,建议迁移到java。时间类。
要了解更多,请参阅Oracle教程。搜索Stack Overflow可以找到很多例子和解释。规范是JSR 310。
从哪里获取java。时间类?
Java SE 8、Java SE 9以及更高版本 内置的。 带有捆绑实现的标准Java API的一部分。 Java 9增加了一些小特性并进行了修复。 Java SE 6和Java SE 7 大部分的java。时间功能在ThreeTen-Backport中向后移植到Java 6和7。 安卓 ThreeTenABP项目将ThreeTen-Backport(上文提到过)专门用于Android。 参见如何使用ThreeTenABP....
ThreeTen-Extra项目扩展了java。额外的课程时间。这个项目是未来可能添加到java.time的一个试验场。你可以在这里找到一些有用的类,比如Interval、YearWeek、YearQuarter等等。