英文:
How do I compare unix timestamps in JavaScript?
问题
我想编写一个类似这样的函数:
function getValuesGreaterThan(num, values);
输入来自系统调用 find . -maxdepth 1 -type f -printf '%C@\n'
,一个字符串数组,类似 [..., "1643764147.7500000000", "1643764147.7600000000", "1643764147.7700000000", ...]
。该函数将返回一个值的数组。
尽管输入是一个字符串数组,但这并不意味着它必须保持不变:如果最简单的解决方案是将其转换为不同类型(例如 number
),那么这也是可以的。返回类型也一样,唯一重要的是以相同的顺序返回正确的子集。
但是,我想确保 getValuesGreaterThan
的输出不受精度问题或强制类型转换怪异问题的影响。
我了解到 JavaScript 有一个 BigInt 类型,但我找不到关于 BigReal
或 BigDecimal
等等的任何信息。我甚至不确定是否需要使用这些;也许 localeCompare
在这些字符串上能够按预期工作?
let getValuesGreaterThan = function (num, values) {
return values.filter((v) => v.localeCompare(num) >= 0)
}
console.log(getValuesGreaterThan("1643764147.7600000000", ["1643764147.7500000000", "1643764147.7600000000", "1643764147.7700000000"]))
它似乎有效,但无论我想到多少实验,都可能会有破坏它的输入。
如何在 JavaScript 中比较 Unix 时间戳?
英文:
I want to write a function that looks like this:
function getValuesGreaterThan(num, values);
The input comes from a system call to find . -maxdepth 1 -type f -printf '%C@\n'
, an array of strings like [..., "1643764147.7500000000", "1643764147.7600000000", "1643764147.7700000000", ...]
. The function will return an array of the values.
Although the input is an array of strings, that doesn't mean it has to stay that way: if the easiest solution to this is to convert it to a different type (e.g., a number
), that's fine. The same goes for the return type--all that matters is the correct subset is returned in the same order.
But, I want to make sure the output of getValuesGreaterThan
isn't affected by precision issues or coercion quirks.
I've learned that JavaScript has a BigInt type, but I can't find anything about a BigReal
or a BigDecimal
, etc. I'm not even sure if I need to use these; perhaps the localeCompare
will work as expected on these strings?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let getValuesGreaterThan = function (num, values) {
return values.filter((v) => v.localeCompare(num) >= 0)
}
console.log(getValuesGreaterThan("1643764147.7600000000", ["1643764147.7500000000", "1643764147.7600000000", "1643764147.7700000000"]))
<!-- end snippet -->
It seems to work, but no matter how many experiments I think of, there could be inputs that break it.
How do I compare unix timestamps in JavaScript?
答案1
得分: 1
- 创建一组阴影字符串,确保所有字符串具有相同的小数部分长度(与最长小数部分长度相同),必要时进行填充。
- 删除小数点。
- 转换为大整数并进行比较。
- 将答案反映回原始字符串。
英文:
- Create a set of shadows strings ensuring all strings have the same fractional component length (the same as longest fractional component length), by padding as required.
- Remove the decimal points.
- Convert to bigint and compare.
- Reflect the answers back to the original strings.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论