我希望从一年中天数中获取的日期名称。示例:2016年第344天的日期名称是什么。我的服务器给我这样的数据&必须用它来找出日期名称。
{
"id": 106,
"month": 12,
"year": 2016,
"yDay": 344,
"hour": 19
}
我可以从日历中获取当前日期。
Calendar calendar = Calendar.getInstance();
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
答案 0 :(得分:2)
首先,您需要使用年份和年份初始化Calendar
实例:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_YEAR, yourDayOfYear);
c.set(Calendar.YEAR, yourYear);
然后您可以从Calendar
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
答案 1 :(得分:2)
通过这样的方式实现目标的一种方法:
public String getNameOfDay(int year, int dayOfYear) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.DAY_OF_YEAR, dayOfYear);
String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
int dayIndex = calendar.get(Calendar.DAY_OF_WEEK);
return days[dayIndex - 1];
}
答案 2 :(得分:0)
您可以从日期(表格日期从yDay,月,年)获得dayOfWeek
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
答案 3 :(得分:0)
您可以直接从Calendar对象获取星期几作为String:
"Québec".mb_chars.upcase
答案 4 :(得分:0)
What is the easiest way to get the current day of the week in Android?
因此,您将获得当天的日期和获得当前日期的方式相同,并以相同的方式获取相同日期的天数。现在就算吧
答案 5 :(得分:0)
试试这个,根据你的年月给你一个名字
oslc
如果你有日期格式,那么你可以尝试这个
// Assuming that you already have this.
int year = 2016;
int month = 12;
int day = 2;
// 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
答案 6 :(得分:0)
实现这一目标的另一种方法是使用Joda Time Package。 Android目前只能在Java 1.7上运行,因此它本身没有很好的时间功能。
将Joda时间添加到build.gradle
:
compile 'joda-time:joda-time:2.9.4'
然后你可以做类似的事情:
public String getNameOfDay(int year, int yDay) {
String pattern = year + ";" + yDay;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("y;D");
DateTime requestedDate = DateTime.parse(pattern, dateTimeFormatter);
int dayOfWeek = requestedDate.getDayOfWeek();
//Notice that Monday is 1 and Sunday is 7
String[] days = {"Monday", "Tuesday", "Thursday", "Friday", "Saturday", "Sunday"};
return days[dayOfWeek - 1];
}
请注意,我只提供了已经发布的实现此目标的方法的替代方案。如果您不想在项目中添加joda时间,您可以选择其他人已经说过的方式。
答案 7 :(得分:0)
这是我使用的方法,并确保您使用相同的格式,这意味着不要使用 -
而不是 /
,反之亦然:
public String getDayName(String date) {
SimpleDateFormat df = new SimpleDateFormat("M-d-yyyy", Locale.getDefault());
Date readDate=null;
try {
readDate = df.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(Objects.requireNonNull(readDate));
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
return days[dayOfWeek-1];
}