亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算自特定日期以來的年月

計算自特定日期以來的年月

森欄 2022-12-22 09:02:08
我剛開始使用 Java Script。我正在嘗試提出一個簡單的解決方案:當前日期 - 格式為“2018 年 1 月 4 日”的指示日期 = 自指示日期以來的年月。我查看了Datejs,但無法弄清楚如何使用它來進行簡單的數學日期計算。我想出了這個,但我不確定這是否是可行的方法。歡迎提出建議。var dPast = 'January 4, 2018'var d1 = new Date(); //"now"var d2 = new Date(dPast);var dCalc = Math.abs((d1-d2)/31556952000);   // difference in millisecondsvar diff = Math.round(10 * dCalc)/10;   // difference in years rounded to tenthalert('It has been ' + diff + ' years since ' + dPast);
查看完整描述

4 回答

?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

最好先從當前日期中減去指定日期的毫秒數,然后將其格式化為您想要的輸出。


var dPast = 'January 5, 2018';

var indicatedD = new Date(dPast);

var d = new Date();


// subtract the current time's milliseconds from the dPast date's.

var elapsed = new Date(d.getTime() - indicatedD.getTime());


// get the years.

var years = Math.abs(elapsed.getUTCFullYear() - 1970);

console.log('It has been ' + years + ' years since ' + dPast);

因為你剛剛起步,所以最好自己探索,但當你適應后,我建議你使用日期庫,例如moment.js,因為它更可靠并且有大量內置方法會讓你的生活更輕松。


查看完整回答
反對 回復 2022-12-22
?
尚方寶劍之說

TA貢獻1788條經驗 獲得超4個贊

可能你可能想檢查 moment.js。它只有 2.6kb 大小,或者你可以使用 cdn


<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

檢查diff功能


var dPast = 'January 4, 2018'

var todaysDate = moment(new Date()); //"now"

var pastDate = moment(new Date(dPast));


var years = todaysDate.diff(pastDate, 'years');

var months = todaysDate.diff(pastDate, 'months');


console.log(years + ' years, ' + months % 12 + ' months');

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>


查看完整回答
反對 回復 2022-12-22
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

原始解決方案可在此處找到:https ://forums.getdrafts.com/t/calculate-years-and-months-since-a-specific-date/8082/3


這段代碼是一個進步,因為我想讓初學者的事情變得簡單。然而,我是一步一步去理解的。我會在這里留下足跡,供我自己參考,也供以后的人參考。


/*********

Day.js is a minimalist JavaScript library that parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API.


Step 1: Download the dayjs.min.js file from the JSDelivr site: https://www.jsdelivr.com/package/npm/dayjs


Step 2 : Save the downloaded file to the Drafts/Library/Scripts folder in iCloud. 

*/


require('dayjs.min.js'); // Tell Drafts to use Dayjs script


let dPast = 'December 4, 2017'; // set the date from the past

let d1 = dayjs(); // tell Dayjs to parse the date

let d2 = dayjs(dPast); // set the current date


/******

* Math.round() - is a function that is used to return a number rounded to the nearest integer (whole) value.


* To get the difference in months, pass the month as the second argument. By default, dayjs#diff will truncate the result to zero decimal places, returning an integer. If you want a floating point number, pass true as the third argument.


*Read more: https://day.js.org/docs/en/display/difference#docsNav

*/


let m = Math.round(d1.diff(d2, 'month', true));


/******

* Divide the number of months (obtained earlier) by 12 to see how many years. This number will be rounded to an integer (whole number). If the result is less than 1 (years) the rounded number will be set to 0. For example 11/12 = 0.916666667 This will be rounded to 0.

*/


let y = Math.floor(m/12); 

if (y == 0) {

  alert(`\n${m} months since ${dPast}`); // Alert that "x" number of months but no years have passed since the indicated date.

}

/* Remainder

An amount left over after division (happens when the first number does not divide exactly by the other). Example: 19 cannot be divided exactly by 5. The closest you can get without going over is 3 x 5 = 15, which is 4 less than 19. So 4 is the remainder.


In JavaScript, the remainder operator (%) returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

*/

else {

  m = m % 12;

  if (m == 0) {

    alert(`${y} years since ${dPast}`); //If the remainder is 0 than a whole year(s) have passed since the indicated date but no months.

  }

  else {

    alert(`${y} years, ${m} months since ${dPast}`); // Years and months since the indicated date.

  }

}



查看完整回答
反對 回復 2022-12-22
?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

這段代碼經過測試可以運行,可以精確到分鐘。


/**

 * 計算日期&時間間隔/推算幾天前后是哪一天

 * @author 江村暮

 */


//平年

const ordinaryYearMonth: Array<any> = [null, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]


//閏年

const leapYearMonth: Array<any> = [null, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]


/**

 * 是否為閏年

 **/

const isLeap = (year: number): boolean => {

    if (year % 400 === 0 && year % 100 === 0) return true

    if (year % 4 === 0 && year % 100 !== 0) return true

    return false

}


//解析時間串

type Num = number

const parseTime = (time: string): {

    hour: Num;

    min: Num

} => {

    var bound: Num = time.indexOf(':')

    return {

        hour: parseInt(time.substring(0, bound)),

        min: parseInt(time.substring(bound + 1))

    }

}


//解析日期串

const parseDate = (date = '2020-03-06'): Readonly<{

    year: number;

    month: number;

    day: number;

    isLeap: boolean

}> => {

    var match = /(\d{4})-(\d{2})-(\d{2})/.exec(date);

    if (!match) throw Error

    return {

        year: parseInt(match[1]),

        month: parseInt(match[2].replace(/^0/, '')),

        day: parseInt(match[3].replace(/^0/, '')),

        isLeap: isLeap(parseInt(match[1]))

    }

}


const calDiffer = (

    defaultDateEarly: string,

    defaultDateLate: string,

    defaultTimeEarly?: string,

    defaultTimeLate?: string

): {

    day: number,

    hour: number,

    min: number,

    overflowHour: number,

    overflowMin: number

} => {


    var dateEarly = parseDate(defaultDateEarly)

        , dateLate = parseDate(defaultDateLate)

        , diffDay: number;


    //兩個日期在同一年

    if (dateLate.year === dateEarly.year) {

        var numOfEarlyMonthDay = dateEarly.isLeap ? leapYearMonth[dateEarly.month] : ordinaryYearMonth[dateEarly.month]

        // 兩個日期在同一月份

        if (dateLate.month === dateEarly.month) {

            diffDay = dateLate.day - dateEarly.day

        } else {

            diffDay = dateLate.day + numOfEarlyMonthDay - dateEarly.day;//兩個日期所在月的非整月天數和

            for (let i = dateEarly.month; i < dateLate.month - 1; i++) {

                diffDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i]

            }

        }

    } else {

        //這一年已過天數

        var lateYearDay = dateLate.day;

        for (let i = dateLate.month - 1; i >= 1; i--) {

            lateYearDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i]

        }

        console.log(lateYearDay)


        //那一年剩下天數

        var earlyYearDay = 0

        for (let i = 13 - dateEarly.month; i >= 1; i--) {

            earlyYearDay += (dateLate.isLeap) ? leapYearMonth[i] : ordinaryYearMonth[i]

        }

        earlyYearDay -= dateEarly.day

        console.log(earlyYearDay)


        //相隔年份天數,如:年份為2010 - 2020,則計算2011 - 2019的天數

        var diffYear: number[] = [];

        for (let i = 0; i <= dateLate.year - dateEarly.year - 1; i++) {

            diffYear.push(dateEarly.year + i + 1)

        }


        diffDay = earlyYearDay + lateYearDay

        diffYear.map(year => {

            diffDay += isLeap(year) ? 366 : 365

        })

    }


    //計算這天剩下的時間與那天已經過的分鐘之和

    var timeEarly = parseTime(defaultTimeEarly || '00:00'),

        timeLate = parseTime(defaultTimeLate || '00:00');

    var overflowDiffMin = 60 * (25 - timeEarly.hour + timeLate.hour) + 60 - timeEarly.min + timeLate.min

    var diffMin = (diffDay - 1) * 1440 + overflowDiffMin

    console.log(timeEarly, timeLate, diffMin)

    return {

        day: diffDay,

        overflowHour: Math.floor(diffMin/60) - diffDay * 24,

        overflowMin: diffMin % 60,//(overflowDiffMin - 1440 * diffDay) % 60,

        hour: Math.floor(diffMin/60),

        min: diffMin % 60

    }

}


export { calDiffer }



查看完整回答
反對 回復 2022-12-22
  • 4 回答
  • 0 關注
  • 141 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號