日期:2014-05-20  浏览次数:20793 次

java关于时间的方法
我想做这样一个方法
取得某一天的上月那天   比如2004/09/25     就得到2004/08/25      
还有就是如果是2004/09/30     那么得到的就是2004/08/31     如果是2004/02/28   得到的就是2004/01/31         这个方法应该怎么写啊       请高手指教下`

------解决方案--------------------
package test1;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class Test16 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
Date dt=new Date();
DateFormat df=new SimpleDateFormat( "yyyy/MM/dd ");
try {
dt=df.parse( "2004/07/31 ");
System.out.println(dt);
Calendar calendar=Calendar.getInstance();
calendar.setTime(dt);
calendar.add(Calendar.MONTH, -1);
System.out.println(calendar.getTime());

} catch (ParseException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}

}

------解决方案--------------------
package test;
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.io.*;
public class test {
public static void main(String[] args) {
SimpleDateFormat format=new SimpleDateFormat( "yyyy/MM/dd ");
try {
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
System.out.println( "请输入年: ");
String year=reader.readLine();
System.out.println( "请输入月: ");
String month=reader.readLine();
System.out.println( "请输入日: ");
String day=reader.readLine();

Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.YEAR,Integer.parseInt(year));
calendar.set(Calendar.MONTH,Integer.parseInt(month)-2);
calendar.set(Calendar.DATE,Integer.parseInt(day));

Date date=calendar.getTime();
System.out.println(format.format(date));
} catch (Exception ex) {

}

}
}
------解决方案--------------------
每个月日子不同~~
------解决方案--------------------
public class C {
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar(Locale.CHINA);
calendar.set(Calendar.DAY_OF_MONTH, 28);
calendar.set(Calendar.MONTH, Calendar.FEBRUARY);
System.out.println(calendar.getTime());
System.out.println(lastMonth(calendar.getTime()));
}

static Date lastMonth(Date date){
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_MONTH);
int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.add(Calendar.MONTH, -1);
if(day == maxDay){
calendar.set(Calendar.DAY_OF_MONTH, calendar.getMaximum(Calendar.DAY_OF_MONTH));
}
return calendar.getTime();
}
}
------解决方案--------------------
拿楼上的东西随便改了改
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.io.*;

public class lastMonthToday {