JavaScript常用时间格式化,时间戳集合

基础版(2023-03-16 22:00:00)

function formatDate(timestamp) {
  var time = String(timestamp).length === 10 ? new Date(parseInt(timestamp) * 1000) : new Date(parseInt(timestamp))
  var y = time.getFullYear() // 年
  var m = time.getMonth() + 1 // 月
  if (m < 10) {
    m = '0' + m
  }
  var d = time.getDate() // 日
  if (d < 10) {
    d = '0' + d
  }
  var h = time.getHours() // 时
  if (h < 10) {
    h = '0' + h
  }
  var mm = time.getMinutes() // 分
  if (mm < 10) {
    mm = '0' + mm
  }
  var s = time.getSeconds() // 秒
  if (s < 10) {
    s = '0' + s
  }
  var timeStr = y + '-' + m + '-' + d + ' ' + h + ':' + mm + ':' + s
  return timeStr
}

倒计时

 function countDown(time) {
        var nowTime = +new Date();
        var inputTime = +new Date(time);
        var times = (inputTime - nowTime) / 1000; //总秒数
        var d = parseInt(times / 60 / 60 / 24); //天数
        var h = parseInt((times / 60 / 60) % 24); //小时
        var m = parseInt((times / 60) % 60); //分钟
        var s = parseInt(times % 60); //秒数
        return d + '天' + h + '时' + m + '分' + s + '秒';
 }

js获取、今日、昨日的开始与结束时间戳(可通过调用方法进行解构取得对应的时间戳)

function getStartEndTime(num = 1) {
  // 一天的毫秒数
  const MillisecondsADay = 24 * 60 * 60 * 1000 * num
  // 今日开始时间戳
  const todayStartTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
  // 今日结束时间戳
  const todayEndTime = new Date(new Date().setHours(23, 59, 59, 999)).getTime()

  // 昨日开始时间戳
  const yesterdayStartTime = todayStartTime - MillisecondsADay
  // 昨日结束时间戳
  const yesterdayEndTime = todayEndTime - MillisecondsADay
  console.log(`
    ${todayStartTime} =>今日时间戳
    ${todayEndTime} => 结束时间戳
    ${yesterdayStartTime} =>  昨日开始时间戳
    ${yesterdayEndTime} =>  昨日结束时间戳
  `)
  return { todayStartTime, todayEndTime, yesterdayStartTime, yesterdayEndTime }
}

js获取当前、今日、本周、本月、本年的时间戳(可通过调用方法进行解构取得对应的时间戳)

function getStartEndTime() {
  // 1、现在的时间
  const nowTime = new Date().getTime()
  // 2、今天开始时间的时间戳
  const todayStartTime = new Date(new Date().toLocaleDateString()).getTime()
  // 3、今天结束时间的时间戳
  const todayEndTime = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1
  // 4、本周开始时间的时间戳
  const thisWeekStart =
    new Date(new Date().toLocaleDateString()).getTime() - (new Date().getDay() - 1) * 24 * 60 * 60 * 1000
  // 5、本周结束时间的时间戳
  const thisWeekEnd = new Date(
    new Date(new Date().setDate(new Date().getDate() + 7 - new Date().getDay() || 7)).setHours(23, 59, 59, 0)
  ).getTime()
  // 6、本月开始时间的时间戳
  const thisMonthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1).getTime()
  // 7、本月结束时间的时间戳
  const thisMonthEnd =
    new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getTime() + 24 * 60 * 60 * 1000 - 1
  // 8、本年开始时间的时间戳
  const thisYearStart = new Date(new Date().getFullYear(), 0).getTime()
  // 9、本年结束时间的时间戳
  const thisYearEnd = new Date(new Date().getFullYear(), 11, 31).getTime() + 24 * 60 * 60 * 1000 - 1
  return {
    nowTime,
    todayStartTime,
    todayEndTime,
    thisWeekStart,
    thisWeekEnd,
    thisMonthStart,
    thisMonthEnd,
    thisYearStart,
    thisYearEnd,
  }
}

js获取每个月的第几个星期的起始时间到结束时间

/**
 * 根据输入年月,每月第几周 返回 这周的时间是从那天到那天
 * @param {string} year
 * @param {string} month 1,2,...,12
 * @param {string} weekday
 */
function getNewWeekTime (year, month, weekday) {
  let from = '' // 这个星期开始日期
  let to = '' // 这个星期结束日期
  var d = new Date()
  d.setFullYear(year, month, 0)
  var monthDays = d.getDate() // 该月天数
  if (weekday === 1) {
    // 第一周
    d.setFullYear(year, month - 1, 1) // 该月第一天
    let w1 = d.getDay() // 获取星期几(0~6) 该月第一天 星期几
    if (w1 === 0) {
      // 如果这个月的一号是这周的最后一天
      from = year + '-' + processTime(month) + '-' + processTime(1)
      to = year + '-' + processTime(month) + '-' + processTime(1)
    } else {
      from = year + '-' + processTime(month) + '-' + processTime(1)
      to = year + '-' + processTime(month) + '-' + processTime(7 - w1 + 1)
    }
  } else if (weekday * 7 >= monthDays) {
    // 最后一周
    d.setFullYear(year, month - 1, monthDays) // 该月最后一天
    let w2 = d.getDay() // 获取星期几(0~6) 该月第一天 星期几
    if (w2 === 0) {
      // 如果是最后一周的第七天
      from = year + '-' + processTime(month) + '-' + processTime(monthDays - 6)
      to = year + '-' + processTime(month) + '-' + processTime(monthDays)
    } else {
      from = year + '-' + processTime(month) + '-' + processTime(monthDays - (w2 - 1))
      to = year + '-' + processTime(month) + '-' + processTime(monthDays)
    }
  } else {
    // 其他周
    d.setFullYear(year, month - 1, 1) // 该月第一天
    let w3 = d.getDay() // 获取星期几(0~6) 该月第一天 星期几
    if (w3 === 0) {
      // 如果是最后一周的第七天
      let endTime = (weekday - 1) * 7 + 1
      let startTime = (weekday - 1) * 7 + 1 - 6
      from = year + '-' + processTime(month) + '-' + processTime(startTime)
      to = year + '-' + processTime(month) + '-' + processTime(endTime)
    } else {
      let endTime = (weekday - 1) * 7 + (7 - w3 + 1)
      let startTime = (weekday - 1) * 7 + (7 - w3 + 1) - 6
      from = year + '-' + processTime(month) + '-' + processTime(startTime)
      to = year + '-' + processTime(month) + '-' + processTime(endTime)
    }
  }

  return {
    from,
    to
  }
}

/**
 * 根据输入 返回需要的日期数据
 * @param {number} days
 * @param {String} 01, ..., 11
 * @returns days
 */
function processTime (days) {
  // 加时间 若小于10号 加0,若大于十号,保持原样
  let str = days + ''
  if (str < 10 && str.length < 2) {
    str = '0' + str
  }
  return str
}

js计算一年有多少周(星期一为第一天)

function getWeeks(year = 2022) {
  // 一年第一天是周几
  var first = new Date(year, 0, 1).getDay()
  if (first == 1) {
    first = 0
  } else if (first == 0) {
    first = 1
  } else {
    first = 8 - first
  }
  // 计算一年有多少天
  if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
    var allyears = 366
  } else {
    var allyears = 365
  }
  // 计算一年有多少周
  var week = Math.ceil((allyears - first) / 7) + (first !== 0 ? 1 : 0)
  return week
}

js计算当前时间的为年的第几周,以及周对应的时间

/*获取当前年的第几周,以及周对应的日期范围(根据当前日期的时间)
*@author weiyongfu
*@date 2017-11-17
*/
function getYearWeekRange(year,weekNum){
    var date=null;
    var year=year;
    var month=null;
    var day=null;
    var d=null;
    if(weekNum==null||weekNum==""){//如果为空,默认加载当前日期,否则加载选择的周数
        date=new Date();//获取系统时间
        year=date.getFullYear();//年
        month=date.getMonth()+1;//月
        day=date.getDate();//
        var d=year+"-"+month+"-"+day;
    }else{
        if(weekNum.length==3){
            weekNum=weekNum.substring(1,2);
        }else if(weekNum.length==4){
            weekNum=weekNum.substring(1,3);
        }
        var weekDay=getDayEveryDay(year,weekNum);
        d=weekDay[0];//获取对应周数的第一天
    }
    //获取当前日期的为今年的第几周的周数,常规的获取直接调用getWeekNumber(year, month, day);
    /*由于项目需要,我这儿的周定义为周五到下周四为一周,所以我传入的日期参数得往前推4天,
    *然后在调用常规的计算周数的方法
    */
    var beforeFourDay=GetDateStr(-4,d);//当前日期前推4天的日期,返回值格式为2017-01-01
    var yearMonthDay=beforeFourDay.split("-");

    if(weekNum==null||weekNum==""){//如果为空,默认加载当前日期的周数以及对应范围,否未为选择的周数
        weekNum=getWeekNumber(yearMonthDay[0], yearMonthDay[1], yearMonthDay[2]);//按照周五到下周四为一周,计算当前日期为今年的第几周
    }else{
        weekNum=weekNum;
    }
    //获取当前日期的为今年的第几周的周数日期范围,getDateRange("2017-01-01"),在调用常规的计算周数日期的方法返回值为["2016-12-26","2017-1-1"];
    /*由于项目需要,我这儿的周定义为周五到下周四为一周,
    *在调用常规的计算周数日期的方法返回值时得相应做出调整getDateRange("2017-01-01");return ["2016-12-26","2017-1-1"];
    * arr[0]前推3天,arr[1]后推5天,["2016-12-30","2017-1-5"],得出2017年的1月1馹,(按照周五到下周四算一周为一周的日期范围为["2016-12-30","2017-1-5"])
    */

    var weekRange=getDateRange(beforeFourDay);//常规的传入时间返回周的范围(周一到周天) return 格式["2016-12-26","2017-1-1"]
    weekRange[0]=GetDateStr(4, weekRange[0]);//后推4天
    weekRange[1]=GetDateStr(4, weekRange[1]);//后推4天


    //返回当前日期为[年,周数,周的范围start,周的范围end],按照周五到下周四为一周
    return [year,weekNum,weekRange[0],weekRange[1]];
}



/*
*这个方法是获取周对应的日期范围(常规的一周为周一到周天为一周
* 参数datevalue如:2017-01-01)
*/
function getDateRange(datevalue){
    var dateValue = datevalue;
    var arr = dateValue.split("-")
    //月份-1 因为月份从0开始 构造一个Date对象
    var date = new Date(arr[0],arr[1]-1,arr[2]);

    var dateOfWeek = date.getDay();//返回当前日期的在当前周的某一天(0~6--周日到周一)

    var dateOfWeekInt = parseInt(dateOfWeek,10);//转换为整型

    if(dateOfWeekInt==0){//如果是周日
        dateOfWeekInt=7;
    }
    var aa = 7-dateOfWeekInt;//当前于周末相差的天数

    var temp2 = parseInt(arr[2],10);//按10进制转换,以免遇到08和09的时候转换成0
    var sunDay = temp2+aa;//当前日期的周日的日期
    var monDay = sunDay-6//当前日期的周一的日期

    var startDate = new Date(arr[0],arr[1]-1,monDay);
    var endDate = new Date(arr[0],arr[1]-1,sunDay);

    var sm = parseInt(startDate.getMonth())+1;//月份+1 因为月份从0开始
    var em = parseInt(endDate.getMonth())+1;

//  alert("星期一的日期:"+startDate.getFullYear()+"-"+sm+"-"+startDate.getDate());
//  alert("星期日的日期:"+endDate.getFullYear()+"-"+em+"-"+endDate.getDate());
    var start = startDate.getFullYear()+"-"+sm+"-"+startDate.getDate();
    var end = endDate.getFullYear()+"-"+em+"-"+endDate.getDate();
    var result = new Array();
    result.push(start);
    result.push(end);

    return result;
}



//以下几个函数是判断当前日期所对应的周数,如2017-1-1,为2017年第一周,return 1
/**
 2  * 判断年份是否为润年
 3  *
 4  * @param {Number} year
 5  */
function isLeapYear(year) {
    return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
/**
 10  * 获取某一年份的某一月份的天数
 11  *
 12  * @param {Number} year
 13  * @param {Number} month
 14  */
function getMonthDays(year, month) {
    return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (isLeapYear(year) ? 29 : 28);
}
/**
 27  * 获取某年的某天是第几周
 28  * @param {Number} y
 29  * @param {Number} m
 30  * @param {Number} d
 31  * @returns {Number}
 32  */
function getWeekNumber(y, m, d) {
    var now = new Date(y, m - 1, d),
        year = now.getFullYear(),
        month = now.getMonth(),
        days = now.getDate();
    //那一天是那一年中的第多少天
    for (var i = 0; i < month; i++) {
        days += getMonthDays(year, i);
    }

    //那一年第一天是星期几
    var yearFirstDay = new Date(year, 0, 1).getDay() || 7;

    var week = null;
    if (yearFirstDay == 1) {
        week = Math.ceil(days / yearFirstDay);
    } else {
        days -= (7 - yearFirstDay + 1);
        week = Math.ceil(days / 7) + 1;
    }

    return week;
}//计算周的范围结束



/*
*js获取当前指定的前几天的日期,往前推4天,GetDateStr(4),后推4天GetDateStr(-4)
 */
function GetDateStr(AddDayCount,date) {
    var dd = new Date(date);
    dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = (dd.getMonth()+1)<10?"0"+(dd.getMonth()+1):(dd.getMonth()+1);//获取当前月份的日期,不足10补0
    var d = dd.getDate()<10?"0"+dd.getDate():dd.getDate();//获取当前几号,不足10补0
    return y+"-"+m+"-"+d;
}



/*
*传入年,周数,获取周数对应的所有日期
 */
var getDayEveryDay = function(year, index) {
    var d = new Date(year, 0, 1);
    while (d.getDay() != 1) {
        d.setDate(d.getDate() + 1);
    }
    var to = new Date(year + 1, 0, 1);
    var i = 1;
    var arr = [];
    for (var from = d; from < to;) {
        if (i == index) {
            arr.push(from.getFullYear() + "-" + (from.getMonth() + 1) + "-" + from.getDate());
        }
        var j = 6;
        while (j > 0) {
            from.setDate(from.getDate() + 1);
            if (i == index) {
                arr.push(from.getFullYear() + "-" + (from.getMonth() + 1) + "-" + from.getDate());
            }
            j--;
        }
        if (i == index) {
            return arr;
        }
        from.setDate(from.getDate() + 1);
        i++;
    }
}

猜你喜欢

转载自blog.csdn.net/yxlyttyxlytt/article/details/129601513
今日推荐