怎么计算自然月,自然季度
搜了点资料没整出来,很久没弄JAVA 了 有点伤
开始时间2011-01-28
结束时间2011-12-02
结果
时间 日 周 月 季度
2011-01-28 1 1 1 1
2011-01-29 2 1 1 1
2011-01-30 3 1 1 1
2011-01-31 4 1 1 1
2011-02-01 5 1 2 1
.........
2011-04-01 63 9 4 2
2011-04-02 64 10 4 2
.......
日和周到是算出来了,,
月和季度 是递增 月是按自然月 如果开始时间是2011-02-02 则月应该也是1 2011-03-01 就是2 类推
季度是在当月的基础上+2 如果开始时间是2011-02-02 则第二个季度是 2011-05-01 类推
------解决方案--------------------
老大,好好看看java的日历类,很多不需要你自己去实现。
//将月份调大一个月,日和周依此类推,不过要注意范围。
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
System.out.println(cal.getTime().toLocaleString());
季度好像默认没有实现,这个你需要自己实现。
以下仅供参考,没有校验。
//获得本季度
public String getThisSeasonTime(int month){
int array[][] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
int season = 1;
if(month>=1&&month<=3){
season = 1;
}
if(month>=4&&month<=6){
season = 2;
}
if(month>=7&&month<=9){
season = 3;
}
if(month>=10&&month<=12){
season = 4;
}
int start_month = array[season-1][0];
int end_month = array[season-1][2];
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");//可以方便地修改日期格式
String years = dateFormat.format(date);
int years_value = Integer.parseInt(years);
int start_days =1;//years+"-"+String.valueOf(start_month)+"-1";//getLastDayOfMonth(years_value,start_month);
int end_days = getLastDayOfMonth(years_value,end_month);
String seasonDate = years_value+"-"+start_month+"-"+start_days+";"+years_value+"-"+end_month+"-"+end_days;
return seasonDate;
}
------解决方案--------------------
for example
Java code
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.setTime(sdf.parse("2011-01-28"));
end.setTime(sdf.parse("2011-12-02"));
int day=1, week=1, month = 1, season=1, lastW=start.get(Calendar.WEEK_OF_YEAR), lastM = start.get(Calendar.MONTH);
System.out.println("时间 日 周 月 季度");
while (!start.after(end)) {
System.out.printf("%s %s %s %s %s\n",
sdf.format(start.getTime()),
day,
week,
month,
season
);
start.add(Calendar.DATE, 1);
day++;
if (start.get(Calendar.WEEK_OF_YEAR) != lastW) {
week++;
lastW = start.get(Calendar.WEEK_OF_YEAR);
}
if (start.get(Calendar.MONTH) != lastM) {
month++;
lastM = start.get(Calendar.MONTH);
if (month%3 == 1) {
season++;
}
}
}
------解决方案--------------------
Java code
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date st = sdf.parse("2011-01-28");
Date ed = sdf.parse("2011-12-02");
Calendar c = Calendar.getInstance();
c.setTime(st);
String rel = "";
int day = 1,week = 1,month = 1,jidu = 1,i=1;
while (st.before(ed)||st.equals(ed)){
rel = sdf.format(c.getTime());
day = c.get(Calendar.DAY_OF_MONTH);
week = c.get(Calendar.WEEK_OF_YEAR);
month = c.get(Calendar.MONTH)+1;
jidu = (month<3)?1:month/3;
System.out.println(rel+"="+i+"="+day+"="+week+"="+month+"="+jidu);
c.add(Calendar.DAY_OF_WEEK, 1);
st = c.getTime();
i++;
}
}