import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Test {
/*
* 将当前日期加减n天数。 如传入整型-5 意为将当前日期减去5天的日期 如传入整型5 意为将当前日期加上5天后的日期 返回字串 例(19990203)
*/
public static Date dateAdd(int days) {
// 日期处理模块 (将日期加上某些天或减去天数)返回字符串
Calendar canlendar = Calendar.getInstance(); // java.util包
canlendar.add(Calendar.DATE, days); // 日期减 如果不够减会将月变动
return canlendar.getTime();
}
public static void main(String[] args) {
Date date = Test.dateAdd(-50);
SimpleDateFormat sdfd = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("50天前日期为:" + sdfd.format(date));
SimpleDateFormat sdf = new SimpleDateFormat("E");
System.out.println("为:" + sdf.format(date));
}
}
使用Calendar 和 SimpleDateFormat两个日期类可搞定!有问题再追问,good luck!
Calendar ca = Calendar.getInstance();
Date now = ca.getTime();
ca.add(Calendar.DAY_OF_MONTH, -50);
Date fu = ca.getTime();
System.out.println("当前日期"+now);
System.out.println("50天以前日期"+fu);
public static void main(String[] args) {
Date date = new Date(); // 新建一个日期
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 格式化日期
String beforeDate = sdf.format(getDateBefore(date, 50));
System.out.println(beforeDate);
String afterDate = getWeekOfDate(sdf.format(getDateAfter(date, 50)));
System.out.println(afterDate);
}
/**
* 得到几天前的时间
*/
public static Date getDateBefore(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
return now.getTime();
}
当前日期是星期几
*/
public static String getWeekOfDate(Date dt) {
String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
return weekDays[w];
}
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_YEAR, -50);
System.out.println(c.getTime());
或者
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, -50);
System.out.println(c.getTime());