写的不好,仅供交流参考。另外所在月份的第一天不都是1号吗
[Java] 纯文本查看 复制代码 /**
* @param args
* @throws ParseException
*
*/
public static void main(String[] args) throws ParseException{
Scanner sc = new Scanner(System.in);
System.out.println("请按格式输入:yyyy-MM-dd");
String s = sc.nextLine();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date();
try{
d = sdf.parse(s);
} catch (ParseException e) {
System.out.println("请按格式输入,错误:" + e.toString() );
//e.printStackTrace();
}
long time = d.getTime();
getlastday(time);
getlastmon(time);
getlastdayofmon(time);
}
private static void getlastdayofmon(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date d = new Date(time);
c.setTime(d);
c.add(Calendar.MONTH, 1);
c.set(Calendar.DATE, 1);
c.add(Calendar.DATE, -1);
System.out.println(sdf.format(c.getTime()));
}
private static void getlastmon(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date d = new Date(time);
c.setTime(d);
c.add(Calendar.MONTH, -1);
System.out.println(sdf.format(c.getTime()));
}
private static void getlastday(long time) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d = new Date(time);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.add(Calendar.DATE, -1);
System.out.println(sdf.format(c.getTime()));
} |