JS 关于时间日期的处理

//n:获取的前几天数
//获取当前日期的前几天
formatDateUtil(n) {
var n = n;
var d = new Date();
var year = d.getFullYear();
var mon = d.getMonth() + 1;
var day = d.getDate();
if (day <= n) {
if (mon > 1) {
mon = mon - 1;
} else {
year = year - 1;
mon = 12;
}
}
d.setDate(d.getDate() - n);
year = d.getFullYear();
mon = d.getMonth() + 1;
day = d.getDate();
let s = year + "-" + (mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day);
return s;
}

/**

  • 从当前日期算起,获取N个月前的日期,日期格式为yyyy-MM-dd
  • java实现
  • @param mon 月份
  • @return
    */
    public static String getDateByMonth(Integer mon) {
    Date date = new Date();
    int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
    int month = Integer.parseInt(new SimpleDateFormat("MM").format(date)) - mon;
    int day = Integer.parseInt(new SimpleDateFormat("dd").format(date));
    if (month == 0) {
    year -= 1;
    month = 12;
    } else if (day > 28) {
    if (month == 2) {
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
    day = 29;
    } else {
    day = 28;
    }
    } else if ((month == 4 || month == 6 || month == 9 || month == 11)
    && day == 31) {
    day = 30;
    }
    }
    String y = year + "";
    String m = "";
    String d = "";
    if (month < 10) {
    m = "00" + month;
    } else {
    m = month + "";
    }
    if (day < 10) {
    d = "0" + day;
    } else {
    d = day + "";
    }
    return y + "-" + m + "-" + d;

/**

  • 从当前日期算起,获取N天前的日期(当前日不算在内),日期格式为yyyy-MM-dd

  • @param daily 天数

  • @return
    */
    public static String getDateByDay(Integer daily) {
    Date date = new Date();
    int year = Integer.parseInt(new SimpleDateFormat("yyyy").format(date));
    int month = Integer.parseInt(new SimpleDateFormat("MM").format(date));
    int day = Integer.parseInt(new SimpleDateFormat("dd").format(date)) - daily;
    if (day < 1) {
    month -= 1;
    if (month == 0) {
    year -= 1;
    month = 12;
    }
    if (month == 4 || month == 6 || month == 9 || month == 11) {
    day = 30 + day;
    } else if (month == 1 || month == 3 || month == 5 || month == 7
    || month == 8 || month == 10 || month == 12) {
    day = 31 + day;
    } else if (month == 2) {
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
    day = 29 + day;
    }
    else {
    day = 28 + day;
    }
    }

    }
    String y = year + "";
    String m = "";
    String d = "";
    if (month < 10) {
    m = "0" + month;
    } else {
    m = month + "";
    }
    if (day < 10) {
    d = "0" + day;
    } else {
    d = day + "";
    }
    return y + "-" + m + "-" + d;
    }

链接:https://www.cnblogs.com/linjiqin/archive/2011/12/05/2276467.html

你可能感兴趣的:(JS 关于时间日期的处理)