我的功能应该采用开始时间戳,结束时间戳和输入日期。这里,开始和结束时间戳可以是任何时间戳(任何时间戳)。
此开始时间戳和结束时间戳将为三周。如果输入的日期属于那个时间戳范围,我需要获得该日期的一周。
example:
start date - 06/08/2011 00:00:00
end Date - 26/08/2011 00:00:00
if entered date - 10/08/2011 This should return week number as 1
if entered date - 27/08/2011 This should return week number as 3.it has to take count of 7 days,from entered date and give the count of week.
以下是我使用的代码。
import java.util.Calendar;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class LocaleTimeSample {
public static void main(String... args) {
try {
String dt = "";
String dt1 = "";
String dt2 = "";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
sdf.setLenient(false);
String givenDateString = "02/06/2016";// given
String startDateString = "01/06/2016";// start
String endDateString = "21/06/2016";// end
Date givenDate = sdf.parse(givenDateString);
Date startDate = sdf.parse(startDateString);
Date endDate = sdf.parse(endDateString);
try {
c.setTime(sdf.parse(startDateString));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("1 Week Date : " + dt);
Date date1 = (Date) sdf.parse(dt);
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt1 = sdf.format(c.getTime());
System.out.println("2 Week Date : " + dt1);
Date date2 = (Date) sdf.parse(dt1);
c.add(Calendar.DAY_OF_MONTH, 7); // number of days to add
dt2 = sdf.format(c.getTime());
System.out.println("2 Week Date : " + dt2);
Date date3 = (Date) sdf.parse(dt2);
if (givenDate.compareTo(date1) <= 0) {
System.out.println("Week 1");
} else if (givenDate.compareTo(date2) <= 0
&& givenDate.compareTo(date1) > 0) {
System.out.println("Week 2");
} else if (givenDate.compareTo(date3) <= 0
&& givenDate.compareTo(date2) > 0) {
System.out.println("Week 3");
}
} catch (ParseException pe) {
pe.printStackTrace();
}
}
}
任何人都可以帮我最小化线路和可重用性评估的代码。
对此有任何想法表示赞赏。
答案 0 :(得分:1)
转换为日期或日历并检索您需要的字段
确认您的日期是字符串这是您必须执行的操作才能将其转换为日期和日历
String startDate = "06/08/2011 00:00:00";
DateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
Date startDateasDate = format.parse(startDate);
Calendar cal = Calendar.getInstance();
cal.setTime(startDateasDate);
然后,您可以使用正确的标记检索所需的日期:
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR);
在这里,您可以看到可用标志的列表:
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
答案 1 :(得分:0)