Front end date operations

Time:2021-5-12

preface

Although there are mature and easy-to-use libraries for date processing, such as (momentum JS and date FNS), sometimes we don’t need the whole library in actual development.
So I sort out the various operations of date and time in front-end development, which is relatively complete. Some of them come from ourselves, and some from our omnipotent netizens~

Gets the current timestamp

var timestamp = Date.parse(new  Date()); // Accurate to seconds
var timestamp = (new Date()).valueOf();  // To the millisecond
var timestamp = new Date().getTime(); // To the millisecond
var timestamp = +new Date();
var timestamp = Date.now();

Gets the specified timestamp

var timestamp = (new Date(" 2019/10/24 08:00:00")).getTime();
var timestamp = (new Date(" 2019-10-24 08:00:00")).getTime();

Gets the time stamp of the day before / after the current time

var timestamp = +new Date() - 24*60*60*1000;
var timestamp = +new Date() + 24*60*60*1000;

Today zero time stamp

var timestamp = new Date(new Date().toLocaleDateString()).getTime();

Time stamp for today’s latest 23:59:59

let timestamp = new Date(new Date().toLocaleDateString()).getTime()+24*60*60*1000-1;

Gets the timestamp n days after the current time

/**
 *@ param {number} n days
 *The return value of @ returns {number} is the time millisecond value
 */
function toNextTimes(n){
    let timestamp = +new Date() + n * 86400000;
    return timestamp;
}

The first day of the week

/***
 *@ return {*} weekfirstday returns the time of the first day of the week
 */
function showWeekFirstDay(){
    let Nowdate=new Date();
    let WeekFirstDay=new Date(Nowdate-(Nowdate.getDay()-1)*86400000);
    return WeekFirstDay;
}

Last day of the week

/***
 *@ return {*} weeklastday returns the time of the last day of the week
 */
function showWeekLastDay(){
    let Nowdate=new Date();
    let WeekFirstDay=new Date(Nowdate-(Nowdate.getDay()-1)*86400000);
    let WeekLastDay=new Date((WeekFirstDay/1000+6*86400)*1000);
    return WeekLastDay;
}

The first day of the month

/***
 *@ return {*} monthfirstday returns the time of the first day of this month
 */
function showMonthFirstDay(){
    let Nowdate=new Date();
    let MonthFirstDay=new Date(Nowdate.getFullYear(),Nowdate.getMonth());
    return MonthFirstDay;
}

Last day of the month

/***
 *@ return {*} monthlastday returns the time of the last day of the month
 */
function showMonthLastDay(){
    let Nowdate=new Date();
    let MonthNextFirstDay=new Date(Nowdate.getFullYear(),Nowdate.getMonth()+1);
    let MonthLastDay=new Date(MonthNextFirstDay-86400000);
    return MonthLastDay;
}

Date to time stamp

/**
 *@ param {string} time - date string, such as' 2018-8-8 ',' 2018,8,8 ',' 2018 / 8 / 8 '
 *The return value of @ returns {number} is the time millisecond value
 */
function timeToTimestamp (time) {
    let date = new Date(time);
    let timestamp = date.getTime();
    return timestamp;
}

Format current time

/***
 *@ return {string} timetext returns the system time string
 */
function getdataTimeSec() {
    let time = new Date();
    let weekDay;
    let year = time.getFullYear();
    let month = time.getMonth() + 1;
    let day = time.getDate();
    //Get time, minutes and seconds
    let h = time.getHours();
    let m = time.getMinutes();
    let s = time.getSeconds();
    //Check if it is less than 10
    h = check(h);
    m = check(m);
    s = check(s);
    let now_day = time.getDay();
    switch (now_day) {
        case 0: {
            Weekday = "Sunday"
        }
            break;
        case 1: {
            Weekday = "Monday"
        }
            break;
        case 2: {
            Weekday = "Tuesday"
        }
            break;
        case 3: {
            Weekday = "Wednesday"
        }
            break;
        case 4: {
            Weekday = "Thursday"
        }
            break;
        case 5: {
            Weekday = "Friday"
        }
            break;
        case 6: {
            Weekday = "Saturday"
        }
            break;
        case 7: {
            Weekday = "Sunday"
        }
            break;
    }
    Let timetext = year + "year" + month + "month" + day + "+ weekday +" + H + ":" + m + ":" + s;

    return timeText
}

Returns the time interval between the specified timestamps

/**
 *Timestamp of the start time of @ param {*} starttime
 *Timestamp of the end time of @ param {*} Endtime
 *@ return {string} STR returns the time string
 */
function getTimeInterval(startTime, endTime) {
    let runTime = parseInt((endTime - startTime) / 1000);
    let year = Math.floor(runTime / 86400 / 365);
    runTime = runTime % (86400 * 365);
    let month = Math.floor(runTime / 86400 / 30);
    runTime = runTime % (86400 * 30);
    let day = Math.floor(runTime / 86400);
    runTime = runTime % 86400;
    let hour = Math.floor(runTime / 3600);
    runTime = runTime % 3600;
    let minute = Math.floor(runTime / 60);
    runTime = runTime % 60;
    let second = runTime;
    let str = '';
    if (year > 0) {
        STR = year +'year ';
    }
    if (year <= 0 && month > 0) {
        STR = month +'month ';
    }
    if (year <= 0 && month <= 0 && day > 0) {
        STR = day +'day ';
    }
    if (year <= 0 && month <= 0 && day <= 0 && hour > 0) {
        STR = hour +'hour ';
    }
    if (year <= 0 && month <= 0 && day <= 0 && hour <= 0 && minute > 0) {
        STR = minute +'minute ';
    }
    if (year <= 0 && month <= 0 && day <= 0 && hour <= 0 && minute <= 0 && second > 0) {
        STR + = second +'second ';
    }
    STR + ='front ';
    return str;
}

Format date by type

/**
 *@ param {*} date specific date variable
 *@ param {string} datetype requires a return type
 *@ return {string} datetext returns the date string in the specified format
 */
function getFormatDate(date, dateType) {
    let dateObj = new Date(date);
    let month = dateObj.getMonth() + 1;
    let strDate = dateObj.getDate();
    let hours = dateObj.getHours();
    let minutes = dateObj.getMinutes();
    let seconds = dateObj.getSeconds();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;

    }
    if (hours >= 0 && hours <= 9) {
        hours = "0" + hours
    }
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes
    }
    if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds
    }

    Let datetext = dateobj. Getfullyear() +'year '+ (dateobj. Getmonth() + 1) +'month' + dateobj. Getdate() +'day ';
    if (dateType == "yyyy-mm-dd") {
        dateText = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dateObj.getDate();
    }
    if (dateType == "yyyy.mm.dd") {
        dateText = dateObj.getFullYear() + '.' + (dateObj.getMonth() + 1) + '.' + dateObj.getDate();
    }
    if (dateType == "yyyy-mm-dd MM:mm:ss") {
        dateText = dateObj.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ":" + minutes + ":" + seconds;
    }
    if (dateType == "mm-dd MM:mm:ss") {
        dateText = month + '-' + strDate + ' ' + hours + ":" + minutes + ":" + seconds;
    }
    If (datetype = = yyyy mm: mm: SS){
        Datetext = dateobj. Getfullyear() +'year '+ month +'month' + strdate +'day '+' + hours + ":" + minutes + ":" + seconds;
    }
    return dateText;
 }

Judge whether it is leap year or not

/**
*@ param {number} year
*@ return {Boolean} returns a Boolean value
*/
function leapYear(year) {
    return !(year % (year % 100 ? 4 : 400));
}

Returns the leap year between two years

/**
*@ param {number} start year
*@ param {number} end end year
*@ return {array} arr returns the array that matches the leap year
*/
function leapYears(start, end) {
    let arr = [];
    for (var i=start; i<end; i++) {
        if ( leapYear(i) ) {
            arr.push(i)
        }
    }
    return arr
}

Judge whether the time format is valid

/**
*Short time, such as (10:24:06)
*@ param {string} STR short time to verify
*@ return {Boolean} returns a Boolean value
*/
function isTime(str) {
    var a = str.match(/^(\d{1,2})(:)?(\d{1,2})(\d{1,2})$/);
    if (a == null) { return false; }
    if (a[1] >= 24 || a[3] >= 60 || a[4] >= 60) {
        return false
    }
    return true;
}

/**
*Short date, like (October 24, 2019)
*@ param {string} STR short time to verify
*@ return {Boolean} returns a Boolean value
*/
function strDateTime(str){
    var result = str.match(/^(\d{1,4})(-|\/)(\d{1,2})(\d{1,2})$/);
    if (result == null) return false;
    var d = new Date(result[1], result[3] - 1, result[4]);
    return (d.getFullYear() == result[1] && d.getMonth() + 1 == result[3] && d.getDate() == result[4]);
}

/**
*Long date and time, like (October 24, 2019 10:24:06)
*@ param {string} STR short time to verify
*@ return {Boolean} returns a Boolean value
*/
function strDateTime(str){
    var result = str.match(/^(\d{4})(-|\/)(\d{1,2})(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})$/);
    if (result == null) return false;
    var d = new Date(result[1], result[3] - 1, result[4], result[5], result[6], result[7]);
    return (d.getFullYear() == result[1] && (d.getMonth() + 1) == result[3] && d.getDate() == result[4] && d.getHours() == result[5] && d.getMinutes() == result[6] && d.getSeconds() == result[7]);
}

Verify date size

/**
*Examples: "October 24, 2019" and "October 25, 2019"
*@ param {string} D1 date to verify 1
*@ param {string} D2 date to verify 2
*@ return {Boolean} returns a Boolean value
*/
function compareDate(d1, d2) {
    return ((new Date(d1.replace(/-/g, "\/"))) < (new Date(d2.replace(/-/g, "\/"))));
}

Verify that a date is today

/**
*@ param {string} Val date to verify
*@ return {Boolean} returns a Boolean value
*/
function isToday(val){
    return new Date().toLocaleDateString() == new Date(val).toLocaleDateString();
}

Verify that the date passed in is yesterday

/**
*@ param {string} Val date to verify
*@ return {Boolean} returns a Boolean value
*/
function isYesterday(val) {
    var today = new Date();
    var yesterday = new Date(now - 1000 * 60 * 60 * 24);
    var test = new Date(val);
    if (yesterday.getYear() === test.getYear() && yesterday.getMonth() === test.getMonth() && yesterday.getDate() === test.getDate()) {
        return true;
    } else {
        return false;
    }
}

Set the date in a few days

/**
*@ param {string} date start date
*Days backward in @ param {number} day
*@ return {string} returns the desired date
*/
function convertDate (date, day) {
    let tempDate = new Date(date);
    tempDate.setDate(tempDate.getDate()+day);
    let Y = tempDate.getFullYear();
    let M = tempDate.getMonth()+1 < 10 ? '0'+(tempDate.getMonth()+1) : tempDate.getMonth()+1;
    let D = tempDate.getDate() < 10 ? '0'+(tempDate.getDate()) : tempDate.getDate();
    let result = Y + "-" + M + "-" + D
    return result;
}

Write at the end

If there is an error in the above function, or there is work encountered, but not written above, welcome to point out~