首先,您有一個從日期轉換而來的序列號,例如:40988 將是 2012 年 3 月 21 日。如果知道序列號是 40988 并且不使用日期物件,我怎么能回傳21 ?我還有 2 個可以使用的其他函式: numberOfDaysYear(year) 回傳特定年份(365 或 366)的天數,我還有 numberOfDaysMonth(month, year) 回傳特定月份的天數和特定年份(31、30、28 或 29)。年限從 1900 一直到 2199,所以這是我開始的
`
//Count the number of 365 years and 366 years
var counterNormalYears = 0
var counterLeapYears = 0
for (let i = 1900; i <= 2199; i ) {
if (numberOfDaysYear(i) == 365) {
counterNormalYears = 1
}
else if (numberOfDaysYear(i) == 366) {
counterLeapYears = 1
}
}
` 從這里繼續,我可以采取什么樣的方法來找到日期的日子而不使用日期物件?
uj5u.com熱心網友回復:
我可能會這樣做
let day = 40988, year = 1899, month = 0;
while (day > 0) day -= numberOfDaysYear( year);
day = numberOfDaysYear(year);
while (day > 0) day -= numberOfDaysMonth( month, year);
day = numberOfDaysMonth(month, year);
解釋 ...
- 從 1899 開始,因為我出于明顯的原因使用了預增量
- 發生的第一件事是從天數中減去 1970 年的天數(使用 YOUR 函式)......因為我使用預增量,所以在第一個回圈中傳入 1970
- 因為我們已經低于零,所以將最后使用的最后天數添加
year回days - 月的類似演算法 - 從天減去直到低于零
- 與步驟 3 中類似的月份回溯
- 你可能需要調整
day2 - 因為數學??
原始代碼中有問題...但這應該可以
我更喜歡使用 Date 雖然
d = new Date('1900-01-01');
d.setDate(40988 1); // because of maths ??
// done
uj5u.com熱心網友回復:
您沒有顯示其他功能,所以我嘲笑了它們。一個簡單的方法是計算自 1900 年以來每年的天數,直到剩下不到 1 年的天數。然后計算每個月的天數,直到剩下的天數少于 1 個月。剩余天數為該月中的某一天。
daysToDate函式將 [year, month, day] 陣列作為數字回傳,以使其更有用。如果您只想要這一天,只需獲取最后一個元素。在示例中,我已將值轉換為 YYYY-MM-DD 時間戳。
它對輸入的驗證最少,可能需要更多。
// Return true if year is a leap year
function isLeap(year) {
return !(year % 4 || !(year % 100) && year % 400);
}
// Return number of days in year
function daysInYear(year) {
return isLeap(year)? 366 : 365;
}
// Return number of days in month
// Month is calendar month number
function daysInMonth(year, month) {
if (month == 2 && isLeap(year)) {
return 29;
}
return [,31,28,31,30,31,30,31,31,30,31,30,31][month];
}
// Convert days since 1900 to [year, month, day]
// Month is calendar month number
// Assumes 1 Jan 1900 is 1
function daysToDate(days) {
// Ensure days is within range 1990-01-01 to 2199-12-31
if (days < 1 || days > 109573) {
return;
}
let daysCounted = 0;
let year = 1900;
// Loop over years until less than a year's worth
// of days left
while (daysInYear(year) < (days - daysCounted)) {
daysCounted = daysInYear(year);
year;
}
let month = 1;
// Loop over month until less than a month's worth
// of days left
while (daysInMonth(year, month) < (days - daysCounted)) {
daysCounted = daysInMonth(year, month);
month;
}
return [year, month, days - daysCounted];
}
[ 1, // 1 Jan 1900
365, // 31 Dec 1900
366, // 1 Jan 1901
730, // 31 Dec 1901
40988, // 21 Mar 2012
109573 // 31 Dec 2199
].forEach(days => console.log(
days ': ' daysToDate(days).map(n=>(n<10?'0':'') n).join('-')
));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/461646.html
標籤:javascript 日期
