欢迎光临殡葬白事网
详情描述
JavaScript时间戳转换工具

我将设计一个直观易用的时间戳转换工具,支持双向转换(时间戳 ↔ 日期时间)并显示多种格式。

设计思路

创建两个主要转换区域:时间戳转日期和日期转时间戳 支持常见时间戳单位(秒、毫秒) 实时显示当前时间戳作为参考 提供多种日期格式显示 添加复制功能方便使用

下面是完整的实现代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>时间戳转换工具</title>
    <style>
        * {
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            background-color: white;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            overflow: hidden;
        }

        header {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            padding: 25px 30px;
            text-align: center;
        }

        h1 {
            margin: 0 0 10px 0;
            font-size: 2.2rem;
        }

        .subtitle {
            font-size: 1.1rem;
            opacity: 0.9;
            margin-bottom: 5px;
        }

        .current-timestamp {
            background-color: rgba(255, 255, 255, 0.15);
            border-radius: 8px;
            padding: 12px;
            margin-top: 15px;
            display: inline-block;
            font-weight: bold;
            font-size: 1.2rem;
        }

        .main-content {
            display: flex;
            flex-wrap: wrap;
            padding: 0;
        }

        .converter-section {
            flex: 1;
            min-width: 300px;
            padding: 30px;
            border-right: 1px solid #eee;
        }

        .converter-section:last-child {
            border-right: none;
        }

        h2 {
            color: #444;
            margin-top: 0;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }

        .input-group {
            margin-bottom: 25px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #555;
        }

        input, select {
            width: 100%;
            padding: 14px;
            border: 2px solid #e1e5eb;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        input:focus, select:focus {
            border-color: #6a11cb;
            outline: none;
        }

        .unit-selector {
            display: flex;
            margin-top: 10px;
            background-color: #f8f9fa;
            border-radius: 8px;
            overflow: hidden;
        }

        .unit-option {
            flex: 1;
            text-align: center;
            padding: 12px;
            cursor: pointer;
            border-right: 1px solid #e1e5eb;
            transition: all 0.2s;
        }

        .unit-option:last-child {
            border-right: none;
        }

        .unit-option:hover {
            background-color: #edf2ff;
        }

        .unit-option.active {
            background-color: #6a11cb;
            color: white;
            font-weight: bold;
        }

        .result {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 18px;
            margin-top: 25px;
            min-height: 120px;
            border: 1px dashed #d1d9e6;
        }

        .result h3 {
            margin-top: 0;
            color: #666;
            font-size: 1rem;
        }

        .result-value {
            font-size: 1.4rem;
            font-weight: bold;
            color: #333;
            word-break: break-all;
            margin: 10px 0;
        }

        .format-options {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
        }

        .format-btn {
            padding: 8px 15px;
            background-color: #f1f3f9;
            border: 1px solid #d1d9e6;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .format-btn:hover {
            background-color: #e2e7f2;
        }

        .format-btn.active {
            background-color: #6a11cb;
            color: white;
            border-color: #6a11cb;
        }

        .action-buttons {
            display: flex;
            gap: 12px;
            margin-top: 20px;
        }

        .btn {
            padding: 14px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.2s;
            flex: 1;
        }

        .btn-primary {
            background-color: #6a11cb;
            color: white;
        }

        .btn-primary:hover {
            background-color: #5a0db3;
        }

        .btn-secondary {
            background-color: #f1f3f9;
            color: #555;
        }

        .btn-secondary:hover {
            background-color: #e2e7f2;
        }

        footer {
            text-align: center;
            padding: 20px;
            color: #777;
            font-size: 0.9rem;
            border-top: 1px solid #eee;
            background-color: #f9fafc;
        }

        @media (max-width: 768px) {
            .main-content {
                flex-direction: column;
            }

            .converter-section {
                border-right: none;
                border-bottom: 1px solid #eee;
            }
        }

        .timestamp-display {
            font-family: monospace;
            background-color: #f8f9fa;
            padding: 5px 10px;
            border-radius: 4px;
            margin: 5px 0;
        }

        .tooltip {
            position: relative;
            display: inline-block;
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            width: 200px;
            background-color: #555;
            color: #fff;
            text-align: center;
            border-radius: 6px;
            padding: 8px;
            position: absolute;
            z-index: 1;
            bottom: 125%;
            left: 50%;
            margin-left: -100px;
            opacity: 0;
            transition: opacity 0.3s;
            font-size: 0.9rem;
            font-weight: normal;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
            opacity: 1;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>时间戳转换工具</h1>
            <div class="subtitle">Timestamp Converter - 支持秒(s)和毫秒(ms)</div>
            <div class="current-timestamp">
                当前时间戳: <span id="current-timestamp-ms"></span> ms / <span id="current-timestamp-s"></span> s
            </div>
        </header>

        <div class="main-content">
            <section class="converter-section">
                <h2>时间戳 → 日期时间</h2>

                <div class="input-group">
                    <label for="timestamp-input">输入时间戳:</label>
                    <input type="number" id="timestamp-input" placeholder="例如: 1659859200">

                    <div class="unit-selector">
                        <div class="unit-option active" data-unit="s">秒 (s)</div>
                        <div class="unit-option" data-unit="ms">毫秒 (ms)</div>
                    </div>
                </div>

                <div class="input-group">
                    <label>目标时区:</label>
                    <select id="timezone-select">
                        <option value="local">本地时区</option>
                        <option value="utc">UTC</option>
                        <option value="zh-CN">北京时间 (GMT+8)</option>
                        <option value="en-US">纽约时间 (GMT-4)</option>
                    </select>
                </div>

                <div class="format-options">
                    <div class="format-btn active" data-format="full">完整格式</div>
                    <div class="format-btn" data-format="date">仅日期</div>
                    <div class="format-btn" data-format="time">仅时间</div>
                    <div class="format-btn" data-format="iso">ISO 格式</div>
                </div>

                <div class="result">
                    <h3>转换结果:</h3>
                    <div id="timestamp-to-date-result" class="result-value">请输入时间戳</div>
                </div>

                <div class="action-buttons">
                    <button id="convert-timestamp-btn" class="btn btn-primary">转换</button>
                    <button id="copy-timestamp-result" class="btn btn-secondary">复制结果</button>
                </div>
            </section>

            <section class="converter-section">
                <h2>日期时间 → 时间戳</h2>

                <div class="input-group">
                    <label for="date-input">选择日期:</label>
                    <input type="date" id="date-input" value="">
                </div>

                <div class="input-group">
                    <label for="time-input">选择时间:</label>
                    <input type="time" id="time-input" value="00:00">
                </div>

                <div class="input-group">
                    <label>输出单位:</label>
                    <div class="unit-selector">
                        <div class="unit-option active" data-unit="s">秒 (s)</div>
                        <div class="unit-option" data-unit="ms">毫秒 (ms)</div>
                    </div>
                </div>

                <div class="result">
                    <h3>转换结果:</h3>
                    <div id="date-to-timestamp-result" class="result-value">请选择日期和时间</div>
                    <div class="format-options">
                        <div class="timestamp-display">秒: <span id="timestamp-s-result">--</span></div>
                        <div class="timestamp-display">毫秒: <span id="timestamp-ms-result">--</span></div>
                    </div>
                </div>

                <div class="action-buttons">
                    <button id="convert-date-btn" class="btn btn-primary">转换</button>
                    <button id="copy-date-result" class="btn btn-secondary">复制时间戳</button>
                </div>
            </section>
        </div>

        <footer>
            <p>时间戳转换工具 &copy; <span id="current-year"></span> | 使用JavaScript编写</p>
            <p class="tooltip">提示: 时间戳是从1970年1月1日00:00:00 UTC开始计算的秒数或毫秒数
                <span class="tooltiptext">Unix时间戳是计算机中记录时间的一种方式,表示从1970年1月1日0时0分0秒UTC开始所经过的秒数或毫秒数。</span>
            </p>
        </footer>
    </div>

    <script>
        // 获取DOM元素
        const timestampInput = document.getElementById('timestamp-input');
        const timestampUnitOptions = document.querySelectorAll('.converter-section:nth-child(1) .unit-option');
        const timezoneSelect = document.getElementById('timezone-select');
        const formatOptions = document.querySelectorAll('.format-btn');
        const convertTimestampBtn = document.getElementById('convert-timestamp-btn');
        const timestampResult = document.getElementById('timestamp-to-date-result');
        const copyTimestampBtn = document.getElementById('copy-timestamp-result');

        const dateInput = document.getElementById('date-input');
        const timeInput = document.getElementById('time-input');
        const dateUnitOptions = document.querySelectorAll('.converter-section:nth-child(2) .unit-option');
        const convertDateBtn = document.getElementById('convert-date-btn');
        const dateResult = document.getElementById('date-to-timestamp-result');
        const timestampSResult = document.getElementById('timestamp-s-result');
        const timestampMsResult = document.getElementById('timestamp-ms-result');
        const copyDateBtn = document.getElementById('copy-date-result');

        const currentTimestampMs = document.getElementById('current-timestamp-ms');
        const currentTimestampS = document.getElementById('current-timestamp-s');
        const currentYear = document.getElementById('current-year');

        // 初始化当前年份
        currentYear.textContent = new Date().getFullYear();

        // 设置默认日期为今天
        const today = new Date();
        const formattedDate = today.toISOString().split('T')[0];
        dateInput.value = formattedDate;

        // 更新当前时间戳
        function updateCurrentTimestamp() {
            const now = new Date();
            const ms = now.getTime();
            const s = Math.floor(ms / 1000);

            currentTimestampMs.textContent = ms.toLocaleString();
            currentTimestampS.textContent = s.toLocaleString();
        }

        // 初始更新和定时更新
        updateCurrentTimestamp();
        setInterval(updateCurrentTimestamp, 1000);

        // 单位选择器功能
        function setupUnitSelector(unitOptions, callback) {
            unitOptions.forEach(option => {
                option.addEventListener('click', function() {
                    unitOptions.forEach(opt => opt.classList.remove('active'));
                    this.classList.add('active');
                    if (callback) callback(this.dataset.unit);
                });
            });
        }

        // 设置时间戳转日期部分的单位选择器
        setupUnitSelector(timestampUnitOptions);

        // 设置日期转时间戳部分的单位选择器
        setupUnitSelector(dateUnitOptions);

        // 格式选择器功能
        formatOptions.forEach(option => {
            option.addEventListener('click', function() {
                formatOptions.forEach(opt => opt.classList.remove('active'));
                this.classList.add('active');
                if (convertTimestampBtn.disabled !== true) {
                    convertTimestamp();
                }
            });
        });

        // 获取当前选择的单位(时间戳转日期部分)
        function getTimestampUnit() {
            const activeOption = document.querySelector('.converter-section:nth-child(1) .unit-option.active');
            return activeOption.dataset.unit;
        }

        // 获取当前选择的单位(日期转时间戳部分)
        function getDateUnit() {
            const activeOption = document.querySelector('.converter-section:nth-child(2) .unit-option.active');
            return activeOption.dataset.unit;
        }

        // 获取当前选择的格式
        function getSelectedFormat() {
            const activeOption = document.querySelector('.format-btn.active');
            return activeOption.dataset.format;
        }

        // 时间戳转日期函数
        function convertTimestamp() {
            const timestampStr = timestampInput.value.trim();

            if (!timestampStr) {
                timestampResult.textContent = "请输入时间戳";
                return;
            }

            const timestamp = parseFloat(timestampStr);
            if (isNaN(timestamp)) {
                timestampResult.textContent = "时间戳格式错误";
                return;
            }

            // 根据单位调整时间戳值
            const unit = getTimestampUnit();
            const timestampMs = unit === 's' ? timestamp * 1000 : timestamp;

            // 创建日期对象
            const date = new Date(timestampMs);

            // 验证日期是否有效
            if (isNaN(date.getTime())) {
                timestampResult.textContent = "无效的时间戳";
                return;
            }

            // 获取选中的时区
            const timezone = timezoneSelect.value;

            // 获取选中的格式
            const format = getSelectedFormat();

            // 根据时区和格式格式化日期
            let formattedDate;

            if (timezone === 'utc') {
                // UTC时间
                switch(format) {
                    case 'full':
                        formattedDate = date.toUTCString();
                        break;
                    case 'date':
                        formattedDate = date.getUTCFullYear() + '-' + 
                                      String(date.getUTCMonth() + 1).padStart(2, '0') + '-' + 
                                      String(date.getUTCDate()).padStart(2, '0');
                        break;
                    case 'time':
                        formattedDate = String(date.getUTCHours()).padStart(2, '0') + ':' + 
                                      String(date.getUTCMinutes()).padStart(2, '0') + ':' + 
                                      String(date.getUTCSeconds()).padStart(2, '0') + ' UTC';
                        break;
                    case 'iso':
                        formattedDate = date.toISOString();
                        break;
                }
            } else if (timezone === 'zh-CN') {
                // 北京时间 (GMT+8)
                const beijingDate = new Date(date.getTime() + 8 * 60 * 60 * 1000);

                switch(format) {
                    case 'full':
                        formattedDate = beijingDate.toUTCString().replace('GMT', 'GMT+8 (北京时间)');
                        break;
                    case 'date':
                        formattedDate = beijingDate.getUTCFullYear() + '-' + 
                                      String(beijingDate.getUTCMonth() + 1).padStart(2, '0') + '-' + 
                                      String(beijingDate.getUTCDate()).padStart(2, '0');
                        break;
                    case 'time':
                        formattedDate = String(beijingDate.getUTCHours()).padStart(2, '0') + ':' + 
                                      String(beijingDate.getUTCMinutes()).padStart(2, '0') + ':' + 
                                      String(beijingDate.getUTCSeconds()).padStart(2, '0') + ' GMT+8';
                        break;
                    case 'iso':
                        formattedDate = beijingDate.toISOString();
                        break;
                }
            } else if (timezone === 'en-US') {
                // 纽约时间 (GMT-4)
                const nyDate = new Date(date.getTime() - 4 * 60 * 60 * 1000);

                switch(format) {
                    case 'full':
                        formattedDate = nyDate.toUTCString().replace('GMT', 'GMT-4 (纽约时间)');
                        break;
                    case 'date':
                        formattedDate = nyDate.getUTCFullYear() + '-' + 
                                      String(nyDate.getUTCMonth() + 1).padStart(2, '0') + '-' + 
                                      String(nyDate.getUTCDate()).padStart(2, '0');
                        break;
                    case 'time':
                        formattedDate = String(nyDate.getUTCHours()).padStart(2, '0') + ':' + 
                                      String(nyDate.getUTCMinutes()).padStart(2, '0') + ':' + 
                                      String(nyDate.getUTCSeconds()).padStart(2, '0') + ' GMT-4';
                        break;
                    case 'iso':
                        formattedDate = nyDate.toISOString();
                        break;
                }
            } else {
                // 本地时间
                switch(format) {
                    case 'full':
                        formattedDate = date.toLocaleString();
                        break;
                    case 'date':
                        formattedDate = date.toLocaleDateString();
                        break;
                    case 'time':
                        formattedDate = date.toLocaleTimeString();
                        break;
                    case 'iso':
                        formattedDate = date.toISOString();
                        break;
                }
            }

            timestampResult.textContent = formattedDate;
        }

        // 日期转时间戳函数
        function convertDateToTimestamp() {
            const dateStr = dateInput.value;
            const timeStr = timeInput.value;

            if (!dateStr) {
                dateResult.textContent = "请选择日期";
                return;
            }

            // 创建日期对象
            const date = new Date(`${dateStr}T${timeStr}`);

            // 验证日期是否有效
            if (isNaN(date.getTime())) {
                dateResult.textContent = "无效的日期或时间";
                return;
            }

            // 计算时间戳
            const timestampMs = date.getTime();
            const timestampS = Math.floor(timestampMs / 1000);

            // 更新结果显示
            dateResult.textContent = `选择的时间: ${date.toLocaleString()}`;
            timestampSResult.textContent = timestampS.toLocaleString();
            timestampMsResult.textContent = timestampMs.toLocaleString();

            // 根据选择的单位高亮显示对应结果
            const unit = getDateUnit();
            if (unit === 's') {
                document.querySelectorAll('.timestamp-display')[0].style.backgroundColor = '#e8f4ff';
                document.querySelectorAll('.timestamp-display')[1].style.backgroundColor = '';
            } else {
                document.querySelectorAll('.timestamp-display')[0].style.backgroundColor = '';
                document.querySelectorAll('.timestamp-display')[1].style.backgroundColor = '#e8f4ff';
            }
        }

        // 复制结果函数
        function copyToClipboard(text, button) {
            navigator.clipboard.writeText(text).then(() => {
                const originalText = button.textContent;
                button.textContent = '已复制!';
                button.style.backgroundColor = '#4CAF50';

                setTimeout(() => {
                    button.textContent = originalText;
                    button.style.backgroundColor = '';
                }, 2000);
            }).catch(err => {
                console.error('复制失败: ', err);
                alert('复制失败,请手动复制文本');
            });
        }

        // 事件监听
        convertTimestampBtn.addEventListener('click', convertTimestamp);

        timestampInput.addEventListener('keyup', function(event) {
            if (event.key === 'Enter') {
                convertTimestamp();
            }
        });

        convertDateBtn.addEventListener('click', convertDateToTimestamp);

        copyTimestampBtn.addEventListener('click', function() {
            const resultText = timestampResult.textContent;
            if (resultText && !resultText.includes("请输入")) {
                copyToClipboard(resultText, this);
            }
        });

        copyDateBtn.addEventListener('click', function() {
            const unit = getDateUnit();
            let timestampToCopy;

            if (unit === 's') {
                timestampToCopy = timestampSResult.textContent;
            } else {
                timestampToCopy = timestampMsResult.textContent;
            }

            if (timestampToCopy && timestampToCopy !== '--') {
                copyToClipboard(timestampToCopy, this);
            }
        });

        // 初始化转换
        convertTimestamp();
        convertDateToTimestamp();

        // 添加输入时实时转换的功能
        timestampInput.addEventListener('input', function() {
            if (this.value.trim() !== '') {
                convertTimestamp();
            } else {
                timestampResult.textContent = "请输入时间戳";
            }
        });

        dateInput.addEventListener('change', convertDateToTimestamp);
        timeInput.addEventListener('change', convertDateToTimestamp);

        // 单位切换时更新结果
        timestampUnitOptions.forEach(option => {
            option.addEventListener('click', function() {
                if (timestampInput.value.trim() !== '') {
                    convertTimestamp();
                }
            });
        });

        dateUnitOptions.forEach(option => {
            option.addEventListener('click', function() {
                convertDateToTimestamp();
            });
        });

        // 时区或格式变化时更新结果
        timezoneSelect.addEventListener('change', function() {
            if (timestampInput.value.trim() !== '') {
                convertTimestamp();
            }
        });
    </script>
</body>
</html>

功能说明

这个时间戳转换工具具有以下功能:

时间戳转日期时间

  • 支持秒和毫秒两种时间戳单位
  • 可选择不同时区:本地时间、UTC、北京时间、纽约时间
  • 支持多种显示格式:完整格式、仅日期、仅时间、ISO格式
  • 实时转换,输入时间戳后立即显示结果

日期时间转时间戳

  • 通过日期选择器和时间选择器选择特定时间
  • 可输出秒或毫秒格式的时间戳
  • 同时显示两种格式的时间戳结果

其他功能

  • 实时显示当前时间戳(每秒更新)
  • 一键复制转换结果
  • 响应式设计,适配各种屏幕尺寸
  • 直观的用户界面和视觉反馈

使用方法

时间戳转日期:在左侧输入时间戳,选择单位(秒/毫秒),选择时区和显示格式,结果会自动显示 日期转时间戳:在右侧选择日期和时间,结果会自动显示秒和毫秒两种格式的时间戳 复制功能:点击"复制结果"或"复制时间戳"按钮可以将结果复制到剪贴板

该工具完全在浏览器中运行,无需网络连接,所有转换操作都在本地JavaScript完成。