android:将任何日期转换为周数

时间:2015-08-17 11:46:13

标签: android calendar

我想知道任何特定日期的一年中的周数。

我试过这个:

int date = 17.08.2015 or date = 17082015
Calendar calendar = Calendar.getInstance(); 
date = calendar.get(Calendar.WEEK_OF_YEAR);

我认为它会起作用,但事实并非如此。

背景:

我有一个DatepickerDialog,用户可以在其中选择日期。但我只需要周数。

提前致谢

4 个答案:

答案 0 :(得分:0)

从谷歌搜索

我找到了this link。请在获得正确的解决方案后检查一下

答案 1 :(得分:0)

它不会那样工作。您需要先解析日期。 看看下面的代码。

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);

因此,当您从Calendar(DatePicker)中选择日期时。只需以特定日期格式格式化该日期并解析它并在Calendar中进行设置。获取周数,就像使用上面的代码一样。

答案 2 :(得分:0)

尝试这个...

   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

答案 3 :(得分:0)

您可以使用此方法获取周数。

public int getDayOfWeek(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        return c.get(Calendar.DAY_OF_WEEK);
}

您必须将格式化日期传递给此方法,并返回周数。

<强> EDIT1:

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();
    }

<强> EDIT2:

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();  
}

我希望它有所帮助!

相关问题