|
1644 | 1644 | "utility"
|
1645 | 1645 | ],
|
1646 | 1646 | "author": "axorax"
|
| 1647 | + }, |
| 1648 | + { |
| 1649 | + "title": "Convert to Unix Timestamp", |
| 1650 | + "description": "Converts a date to a Unix timestamp in seconds.", |
| 1651 | + "code": [ |
| 1652 | + "/**", |
| 1653 | + " * Converts a date string or Date object to Unix timestamp in seconds.", |
| 1654 | + " *", |
| 1655 | + " * @param {string|Date} input - A valid date string or Date object.", |
| 1656 | + " * @returns {number} - The Unix timestamp in seconds.", |
| 1657 | + " * @throws {Error} - Throws an error if the input is invalid.", |
| 1658 | + " */", |
| 1659 | + "function convertToUnixSeconds(input) {", |
| 1660 | + " if (typeof input === 'string') {", |
| 1661 | + " if (!input.trim()) {", |
| 1662 | + " throw new Error('Date string cannot be empty or whitespace');", |
| 1663 | + " }", |
| 1664 | + " } else if (!input) {", |
| 1665 | + " throw new Error('Input is required');", |
| 1666 | + " }", |
| 1667 | + "", |
| 1668 | + " let date;", |
| 1669 | + "", |
| 1670 | + " if (typeof input === 'string') {", |
| 1671 | + " date = new Date(input);", |
| 1672 | + " } else if (input instanceof Date) {", |
| 1673 | + " date = input;", |
| 1674 | + " } else {", |
| 1675 | + " throw new Error('Input must be a valid date string or Date object');", |
| 1676 | + " }", |
| 1677 | + "", |
| 1678 | + " if (isNaN(date.getTime())) {", |
| 1679 | + " throw new Error('Invalid date provided');", |
| 1680 | + " }", |
| 1681 | + "", |
| 1682 | + " return Math.floor(date.getTime() / 1000);", |
| 1683 | + "}", |
| 1684 | + "", |
| 1685 | + "// Usage", |
| 1686 | + "console.log(convertToUnixSeconds('2025-01-01T12:00:00Z')); // 1735732800", |
| 1687 | + "console.log(convertToUnixSeconds(new Date('2025-01-01T12:00:00Z'))); // 1735732800", |
| 1688 | + "console.log(convertToUnixSeconds(new Date())); //Current Unix timestamp in seconds (varies depending on execution time)" |
| 1689 | + ], |
| 1690 | + "tags": [ |
| 1691 | + "javascript", |
| 1692 | + "date", |
| 1693 | + "unix", |
| 1694 | + "timestamp", |
| 1695 | + "utility" |
| 1696 | + ], |
| 1697 | + "author": "Yugveer06" |
1647 | 1698 | }
|
1648 | 1699 | ]
|
1649 | 1700 | },
|
|
0 commit comments