I'd like to find out the week number of the year from any given date.
I've tried this:
int date = 17.08.2015 or date = 17082015
Calendar calendar = Calendar.getInstance();
date = calendar.get(Calendar.WEEK_OF_YEAR);
I thought it would work, but it did not.
Background:
I have a DatepickerDialog where the user can select the date. But I just need the weeknumber.
Thanks in advance
It wont work like that. You need to parse the date first. Have a look at the following code.
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);
So when you select a date from Calendar (DatePicker). Just format that date in a particular date format and parse it and set it in Calendar
. Get the week number like using above code.
try this one...
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();
}
for more info try this link for simple date format: http://developer.android.com/reference/java/text/SimpleDateFormat.html
You can get week number using this method.
public int getDayOfWeek(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.DAY_OF_WEEK);
}
you have to pass formatted date to this method and it returns week number.
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();
}
I hope it helps!
If you want you can also try this so you can get your current date as variable
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);
从谷歌搜索我找到了这个链接。一旦你能得到正确的解决方案,请检查这个
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.