我正在尋找一種在 javascript 中復制 oracle TRUNC 日期函式的方法
https://www.techonthenet.com/oracle/functions/trunc_date.php
基本上它在最后一個時間間隔四舍五入一個unix時間戳(圓形時間11pm到4hrs將導致8pm)
我的第一次嘗試是:
const trunc = (ts,candleSize) => (Math.floor((ts)/(candleSize)) * candleSize)
但這僅適用于最多 1 小時的間隔。
例子: trunc(Date('2021-01-01T13:17:00'), 5*60) === Date('2021-01-01T13:15:00')
但 trunc(Date('2021-01-01T13:16:00'), 60*60*4) !== Date('2021-01-01T12:00:00')
所以我嘗試使用模數:
const trunc = (ts,candleSize) => (ts - (ts % candleSize)
它適用于大多數間隔示例:``
但我仍然無法做(季度)或(一個月的第一天)或一周的第一天之類的事情
uj5u.com熱心網友回復:
我不知道 Oracle 的 TRUNC 究竟是如何作業的,但這里有一些可能適合的東西。它將截斷 (floor) 到指定單位的任意倍數,例如,世紀的開始是“年*100”,季度的開始是“月*3”,等等。缺少的倍數是 1,所以“月”相當于“月*1”。
/* Truncate date to previous full unit, does not
* modify passed date.
* Start of week is Monday.
*
* @param {Date} date - date to truncate
* @param {string} unit - one of: year, month, week,
* day, hour, minute, second
* optional subunit separated by *
* hour*12 = trunc to nearest whole multiple of 12 hours
* minute*10 = trunc to nearest whole multiple of 10 minutes
*
* @returns {Date} truncated Date
*/
function trunc(date = new Date(), unit = 'day') {
let d = new Date( date);
// Parse unit & subunit
unit = unit.toLowerCase();
let [u, uSub] = unit.split('*');
// Deal with invalid or missing sub unit
if (!Number.isInteger( uSub)) uSub = 1;
// Truncating functions
let f = {
year: d => [d.getFullYear() - d.getFullYear() % uSub, 0],
month: d => [d.getFullYear(), d.getMonth() - d.getMonth() % uSub],
// Start of week is Monday
week: d => [d.getFullYear(), d.getMonth(), d.getDate() - d.getDay() 1],
day: d => [d.setHours(0,0,0,0)],
hour: d => [d.setHours(d.getHours() - d.getHours() % uSub, 0,0,0)],
minute: d => [d.setMinutes(d.getMinutes() - d.getMinutes() % uSub, 0,0)],
second: d => [d.setSeconds(d.getSeconds() - d.getSeconds() % uSub)],
millisecond: d => [d.setMilliseconds(d.getMilliseconds() - d.getMilliseconds() % uSub)]
};
// Validate unit & call appropriate function
if (f.hasOwnProperty(u)) {
return new Date(...f[u](d));
}
// If invalid unit, return undefined
}
// Examples
let d = new Date(2019, 11, 15, 23, 59, 41, 55);
console.log('Test date => ' d.toString());
'year*100 year*10 year month*3 month week day hour*12 hour*6 hour*4 hour*3 hour*2 hour minute*30 minute*20 minute*15 minute*10 minute*5 minute second*30 second'.split(' ')
.forEach(
unit => console.log(`${unit} => ${trunc(d, unit).toString()}`)
);
// Default (start of today)
console.log(`Default => ${trunc().toString()}`)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/327961.html
標籤:javascript 甲骨文 日期
