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

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,用户可以在其中 select 日期。但我只需要周数。

提前致谢

从 google 搜索中我找到了 this link。请在找到正确的解决方案后检查一下

这样不行。您需要先解析日期。 看看下面的代码。

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

因此,当您 select 来自日历 (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();
        }  

有关更多信息,请尝试使用此 link 简单日期格式: 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);
}

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

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