[英]android: Convert any date into week number
我想从任何给定日期找出一年中的周数。
我试过这个:
int date = 17.08.2015 or date = 17082015
Calendar calendar = Calendar.getInstance();
date = calendar.get(Calendar.WEEK_OF_YEAR);
我以为它会起作用,但它没有。
背景:
我有一个 DatepickerDialog,用户可以在其中选择日期。 但我只需要周数。
提前致谢
它不会那样工作。 您需要先解析日期。 看看下面的代码。
String strDate = "17.08.2015";
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Date date = null
try{
date = dateFormat.parse(strDate)
}
catch(Exception e){
e.printStackTrace();
}
Calendar now = Calendar.getInstance();
now.setTime(date);
int week = now.get(Calendar.WEEK_OF_YEAR);
因此,当您从日历 (DatePicker) 中选择日期时。 只需以特定日期格式格式化该日期并解析它并将其设置在Calendar
。 像使用上面的代码一样获取周数。
试试这个...
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar=Calendar.getInstance();
String demoDate="2015-01-15 11:09:00";
try{
calendar.setTime(dateFormat.parse(demoDate));
int weekOfYear=Calendar.WEEK_OF_YEAR);
}catch(Exception e){
e.printStackTrace();
}
有关更多信息,请尝试使用此链接获取简单的日期格式: http : //developer.android.com/reference/java/text/SimpleDateFormat.html
您可以使用此方法获取周数。
public int getDayOfWeek(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.DAY_OF_WEEK);
}
您必须将格式化的日期传递给此方法并返回周数。
编辑1:
SimpleDateFormat format = new SimpleDateFormat("EEEE", Locale.getDefault());;
Date date;
Calendar calendar = Calendar.getInstance();
try {
date = format.parse(format.format(calendar.getTime()));
int weekDay = getDayOfWeek(date);
} catch (ParseException e) {
e.printStackTrace();
}
编辑2:
String dtStart = "2010-10-15";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date date = format.parse(dtStart);
//this date can be passed to getDayOfWeek method
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
我希望它有帮助!
如果你愿意,你也可以试试这个,这样你就可以将当前日期作为变量
DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String date_posted = df.format(Calendar.getInstance().getTime());
Date date = null;
try {
date = df.parse(date_posted);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar now = Calendar.getInstance();
now.setTime(date);
int week = now.get(Calendar.WEEK_OF_YEAR);
从谷歌搜索我找到了这个链接。一旦你能得到正确的解决方案,请检查这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.