[英]get start and end date of the week
实际上,我想显示一组数据,其中包含特定日期的一周的开始和结束日期。 在我的模拟器中,它的工作正常。 例如。 如果我给4月23日,它给我一周的开始日期为4月22日,结束日期为4月28日,但是如果我尝试在我的设备中构建相同的代码,则它显示的一周的开始日期为4月27日,结束日期为28四月
我正在使用的一段代码:
//to get first day of week
cal1.set(Calendar.DAY_OF_WEEK, 1);
int day1 = cal1.get(Calendar.DAY_OF_MONTH);
//to get last day of week
cal1.set(Calendar.DAY_OF_WEEK, 7);
int day7 = cal1.get(Calendar.DAY_OF_MONTH);
我不知道为什么要得到这些数据,但这是我得到第一个和最后一个日期的方式,请看一下可能会有所帮助。 (它的写法给出了本周的开始和结束日期,因此可能需要稍作调整。)
日历calendar = Calendar.getInstance();
Date date1 = calendar.getTime();
//current date to check that our week lies in same month or not
SimpleDateFormat checkformate = new SimpleDateFormat("MM/yyyy");
String currentCheckdate= checkformate.format(date1);
int weekn = calendar.get(Calendar.WEEK_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
//resat calender without date
calendar.clear();
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.set(Calendar.WEEK_OF_MONTH,weekn);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.YEAR,year);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date datef = calendar.getTime();
//move date to 6 days + to get last date of week
Long timeSixDayPlus = calendar.getTimeInMillis()+518400000L;
Date dateL = new Date(timeSixDayPlus);
String firtdate = simpleDateFormat.format(datef);
String lastdate = simpleDateFormat.format(dateL);
String firtdateCheck = checkformate.format(datef);
String lastdateCheck = checkformate.format(dateL);
//if our week lies in two different months then we show only current month week part only
if (!firtdateCheck.toString().equalsIgnoreCase(currentCheckdate)) {
firtdate = "1" + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.YEAR);
}
if (!lastdateCheck.toString().equalsIgnoreCase(currentCheckdate)) {
int ma = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
lastdate = String.valueOf(ma) + "/" + calendar.get(Calendar.MONTH) + "/" + calendar.get(Calendar.YEAR);
}
Log.e("current","=>>"+firtdate+" to "+lastdate);
要获得一周的第一天-
得到相应的日期 。
Calendar calendar = Calendar.getInstance(); //optional step calendar.setFirstDayOfWeek(Calendar.SUNDAY); calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); int firstDateOfWeek = calendar.get(Calendar.DATE);
要获取一周的最后日期-
获取相应的日期。
Calendar calendar = Calendar.getInstance(); //optional step calendar.setFirstDayOfWeek(Calendar.SUNDAY); calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY); int lastDateOfWeek = calendar.get(Calendar.DATE);
通过这种方式,您可以获取每周的第一和最后一个日期。 请记住,我将一周的第一天设置为SUNDAY。 根据您的需要进行设置。 尽管设置一周的第一天是完全可选的。 这使您的代码更加透明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.