[英]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.