例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
例如,我有日期:“23/2/2010”(2010年2月23日)。我想把它传递给一个返回星期几的函数。我该怎么做呢?
在这个例子中,函数应该返回String "Tue"。
此外,如果只需要日期顺序,如何检索?
当前回答
//to get day of any date
import java.util.Scanner;
import java.util.Calendar;
import java.util.Date;
public class Show {
public static String getDay(String day,String month, String year){
String input_date = month+"/"+day+"/"+year;
Date now = new Date(input_date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
int final_day = (calendar.get(Calendar.DAY_OF_WEEK));
String finalDay[]={"SUNDAY","MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY"};
System.out.println(finalDay[final_day-1]);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
getDay(day, month, year);
}
}
其他回答
博士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等等。
添加了另一种完全符合OP要求的方法,而不使用最新的内置方法:
public static String getDay(String inputDate) {
String dayOfWeek = null;
String[] days = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
try {
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date dt1 = format1.parse(inputDate);
dayOfWeek = days[dt1.getDay() - 1];
} catch(Exception e) {
System.out.println(e);
}
return dayOfWeek;
}
有一个关于hackerrank Java日期和时间的挑战
就我个人而言,我更喜欢LocalDate类。
进口java.time.LocalDate 使用“of”方法检索localDate,该方法包含3个参数 “int”格式。 最后,使用“getDayOfWeek”方法获取当天的名称。
有一个关于这个挑战的视频。
Java日期和时间Hackerrank解决方案
我希望它会有所帮助:)
是的。根据具体情况:
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
另一个“有趣”的方法是使用末日算法。这是一个更长的方法,但如果您不需要用给定的日期创建Calendar对象,那么它也更快。
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
*
* @author alain.janinmanificat
*/
public class Doomsday {
public static HashMap<Integer, ArrayList<Integer>> anchorDaysMap = new HashMap<>();
public static HashMap<Integer, Integer> doomsdayDate = new HashMap<>();
public static String weekdays[] = new DateFormatSymbols(Locale.FRENCH).getWeekdays();
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException, ParseException {
// Map is fed manually but we can use this to calculate it : http://en.wikipedia.org/wiki/Doomsday_rule#Finding_a_century.27s_anchor_day
anchorDaysMap.put(Integer.valueOf(0), new ArrayList<Integer>() {
{
add(Integer.valueOf(1700));
add(Integer.valueOf(2100));
add(Integer.valueOf(2500));
}
});
anchorDaysMap.put(Integer.valueOf(2), new ArrayList<Integer>() {
{
add(Integer.valueOf(1600));
add(Integer.valueOf(2000));
add(Integer.valueOf(2400));
}
});
anchorDaysMap.put(Integer.valueOf(3), new ArrayList<Integer>() {
{
add(Integer.valueOf(1500));
add(Integer.valueOf(1900));
add(Integer.valueOf(2300));
}
});
anchorDaysMap.put(Integer.valueOf(5), new ArrayList<Integer>() {
{
add(Integer.valueOf(1800));
add(Integer.valueOf(2200));
add(Integer.valueOf(2600));
}
});
//Some reference date that always land on Doomsday
doomsdayDate.put(Integer.valueOf(1), Integer.valueOf(3));
doomsdayDate.put(Integer.valueOf(2), Integer.valueOf(14));
doomsdayDate.put(Integer.valueOf(3), Integer.valueOf(14));
doomsdayDate.put(Integer.valueOf(4), Integer.valueOf(4));
doomsdayDate.put(Integer.valueOf(5), Integer.valueOf(9));
doomsdayDate.put(Integer.valueOf(6), Integer.valueOf(6));
doomsdayDate.put(Integer.valueOf(7), Integer.valueOf(4));
doomsdayDate.put(Integer.valueOf(8), Integer.valueOf(8));
doomsdayDate.put(Integer.valueOf(9), Integer.valueOf(5));
doomsdayDate.put(Integer.valueOf(10), Integer.valueOf(10));
doomsdayDate.put(Integer.valueOf(11), Integer.valueOf(7));
doomsdayDate.put(Integer.valueOf(12), Integer.valueOf(12));
long time = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
//Get a random date
int year = 1583 + new Random().nextInt(500);
int month = 1 + new Random().nextInt(12);
int day = 1 + new Random().nextInt(7);
//Get anchor day and DoomsDay for current date
int twoDigitsYear = (year % 100);
int century = year - twoDigitsYear;
int adForCentury = getADCentury(century);
int dd = ((int) twoDigitsYear / 12) + twoDigitsYear % 12 + (int) ((twoDigitsYear % 12) / 4);
//Get the gap between current date and a reference DoomsDay date
int referenceDay = doomsdayDate.get(month);
int gap = (day - referenceDay) % 7;
int result = (gap + adForCentury + dd) % 7;
if(result<0){
result*=-1;
}
String dayDate= weekdays[(result + 1) % 8];
//System.out.println("day:" + dayDate);
}
System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 80
time = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
Calendar c = Calendar.getInstance();
//I should have used random date here too, but it's already slower this way
c.setTime(new SimpleDateFormat("dd/MM/yyyy").parse("12/04/1861"));
// System.out.println(new SimpleDateFormat("EE").format(c.getTime()));
int result2 = c.get(Calendar.DAY_OF_WEEK);
// System.out.println("day idx :"+ result2);
}
System.out.println("time (ms) : " + (System.currentTimeMillis() - time)); //time (ms) : 884
}
public static int getADCentury(int century) {
for (Map.Entry<Integer, ArrayList<Integer>> entry : anchorDaysMap.entrySet()) {
if (entry.getValue().contains(Integer.valueOf(century))) {
return entry.getKey();
}
}
return 0;
}
}