用java程序写 使用日期类计算当前日期的前50天是哪一天,是星期几

2024-11-24 01:57:21
推荐回答(4个)
回答1:

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!

回答2:

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);

回答3:

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];
}

回答4:

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());