Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

将 Date 对象转换为 Unix 时间戳; 输出长度为 10 位或 13 位的时间戳 #23

Merged
merged 1 commit into from
Jul 30, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
将 Date 对象转换为 Unix 时间戳; 输出长度为 10 位或 13 位的时间戳
  • Loading branch information
penn201500 committed Jul 30, 2024
commit 7e62af29872825a8c5f90e613462fb85f26caea6
34 changes: 34 additions & 0 deletions yd_datetime_dateToTimestamp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* 将 Date 对象转换为 Unix 时间戳。
* 验证 Date 对象是否有效,并允许选择输出时间戳的精度(秒或毫秒)。
* 该函数将验证输入的 Date 对象是否表示有效的日期。
* @author penn <https://github.com/penn201500>
* @category 日期时间
* @param {Date} date - Date 对象。
* @param {boolean} inMilliseconds - 如果为 true,则输出 13 位数字的时间戳(毫秒级),否则输出 10 位数字的时间戳(秒级)。默认为 false。
* @returns {number|null} 对应的 Unix 时间戳,如果 Date 对象无效则返回 null。
*
* @example
* // 示例: 有效的 Date 对象,输出秒级时间戳
* console.log(dateToTimestamp(new Date())) // 输出: Unix 时间戳(10位数字)
*
* @example
* // 示例: 有效的 Date 对象,输出毫秒级时间戳
* console.log(dateToTimestamp(new Date(), true)) // 输出: Unix 时间戳(13位数字)
*
* @example
* // 示例: 无效的 Date 对象
* console.log(dateToTimestamp(new Date("invalid"))) // 输出: null
*
* @example
* // 示例: 显然无效的 Date 对象
* console.log(dateToTimestamp(new Date('1000-00-00 00:00:00Z'))) // 输出: null
*/
export const dateToTimestamp = (date, inMilliseconds = false) => {
// Check if 'date' is an instance of Date and it represents a valid date
if (!(date instanceof Date) || isNaN(date.getTime())) {
console.error("Invalid Date object.")
return null
}
return inMilliseconds ? date.getTime() : Math.floor(date.getTime() / 1000)
}