时间转时间戳代码示例大全

更新时间:

时间转时间戳编程开发参考指南

时间转时间戳代码示例大全提供各种主流编程语言将日期时间转换为Unix时间戳的完整代码示例,包括JavaScript、Python、Java、PHP、Go、C#等语言的实现方法,全面支持生成10位秒级和13位毫秒级时间戳,是开发者必备的参考资料。

⏰ 时间转时间戳代码示例大全

将日期时间转换为Unix时间戳是开发中的常见需求,本文为开发者提供各种主流编程语言将时间转换为时间戳的完整代码示例。所有代码示例均全面支持生成10位秒级时间戳13位毫秒级时间戳,涵盖当前时间获取、指定时间转换等实用场景。

🌐 JavaScript 时间转时间戳

JavaScript 时间转时间戳
// 获取当前时间戳
const nowTimestamp = Date.now(); // 13位毫秒级
console.log(nowTimestamp); // 1642857600000

const nowTimestampSec = Math.floor(Date.now() / 1000); // 10位秒级
console.log(nowTimestampSec); // 1642857600

// 指定日期转时间戳
const date = new Date('2022-01-22 16:00:00');
const timestamp = date.getTime(); // 13位毫秒级
console.log(timestamp); // 1642857600000

const timestampSec = Math.floor(timestamp / 1000); // 10位秒级
console.log(timestampSec); // 1642857600

// 从年月日时分秒创建时间戳
const customDate = new Date(2022, 0, 22, 16, 0, 0); // 月份从0开始
const customTimestamp = customDate.getTime();
console.log(customTimestamp); // 1642857600000

// UTC时间转时间戳
const utcTimestamp = Date.UTC(2022, 0, 22, 8, 0, 0); // UTC时间
console.log(utcTimestamp); // 1642857600000

🐍 Python 时间转时间戳

Python 时间转时间戳
import time
from datetime import datetime, timezone
import calendar

# 获取当前时间戳
now_timestamp = int(time.time())  # 10位秒级
print(now_timestamp)  # 1642857600

now_timestamp_ms = int(time.time() * 1000)  # 13位毫秒级
print(now_timestamp_ms)  # 1642857600000

# 指定时间转时间戳
dt = datetime(2022, 1, 22, 16, 0, 0)
timestamp = int(dt.timestamp())
print(timestamp)  # 1642857600

# 字符串时间转时间戳
time_str = '2022-01-22 16:00:00'
dt = datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S')
timestamp = int(dt.timestamp())
print(timestamp)  # 1642857600

# UTC时间转时间戳
utc_dt = datetime(2022, 1, 22, 8, 0, 0, tzinfo=timezone.utc)
utc_timestamp = int(utc_dt.timestamp())
print(utc_timestamp)  # 1642857600

# 使用calendar模块
timestamp_cal = calendar.timegm(dt.timetuple())
print(timestamp_cal)  # 1642857600

☕ Java 时间转时间戳

Java 时间转时间戳
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class TimeToTimestamp {
    public static void main(String[] args) {
        // 获取当前时间戳
        long nowTimestamp = Instant.now().getEpochSecond(); // 10位秒级
        System.out.println(nowTimestamp); // 1642857600
        
        long nowTimestampMs = Instant.now().toEpochMilli(); // 13位毫秒级
        System.out.println(nowTimestampMs); // 1642857600000
        
        // 指定时间转时间戳
        LocalDateTime dateTime = LocalDateTime.of(2022, 1, 22, 16, 0, 0);
        long timestamp = dateTime.toEpochSecond(ZoneOffset.ofHours(8));
        System.out.println(timestamp); // 1642857600
        
        // 字符串时间转时间戳
        String timeStr = "2022-01-22 16:00:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parsedDateTime = LocalDateTime.parse(timeStr, formatter);
        long parsedTimestamp = parsedDateTime.toEpochSecond(ZoneOffset.ofHours(8));
        System.out.println(parsedTimestamp); // 1642857600
        
        // 使用传统Date类
        Date date = new Date();
        long dateTimestamp = date.getTime() / 1000; // 10位秒级
        System.out.println(dateTimestamp);
    }
}

🐘 PHP 时间转时间戳

PHP 时间转时间戳
<?php
// 获取当前时间戳
$nowTimestamp = time(); // 10位秒级
echo $nowTimestamp; // 1642857600

$nowTimestampMs = round(microtime(true) * 1000); // 13位毫秒级
echo $nowTimestampMs; // 1642857600000

// 指定时间转时间戳
$timestamp = mktime(16, 0, 0, 1, 22, 2022);
echo $timestamp; // 1642857600

// 字符串时间转时间戳
$timeStr = '2022-01-22 16:00:00';
$timestamp = strtotime($timeStr);
echo $timestamp; // 1642857600

// 使用DateTime类
$dateTime = new DateTime('2022-01-22 16:00:00');
$timestamp = $dateTime->getTimestamp();
echo $timestamp; // 1642857600

// 从格式化字符串创建
$dateTime = DateTime::createFromFormat('Y-m-d H:i:s', '2022-01-22 16:00:00');
$timestamp = $dateTime->getTimestamp();
echo $timestamp; // 1642857600

// UTC时间
$utcDateTime = new DateTime('2022-01-22 08:00:00', new DateTimeZone('UTC'));
$utcTimestamp = $utcDateTime->getTimestamp();
echo $utcTimestamp; // 1642857600
?>

🐹 Go 时间转时间戳

Go 时间转时间戳
package main

import (
    "fmt"
    "time"
)

func main() {
    // 获取当前时间戳
    now := time.Now()
    nowTimestamp := now.Unix() // 10位秒级
    fmt.Println(nowTimestamp) // 1642857600
    
    nowTimestampMs := now.UnixMilli() // 13位毫秒级
    fmt.Println(nowTimestampMs) // 1642857600000
    
    // 指定时间转时间戳
    t := time.Date(2022, 1, 22, 16, 0, 0, 0, time.Local)
    timestamp := t.Unix()
    fmt.Println(timestamp) // 1642857600
    
    // 字符串时间转时间戳
    timeStr := "2022-01-22 16:00:00"
    parsedTime, _ := time.Parse("2006-01-02 15:04:05", timeStr)
    parsedTimestamp := parsedTime.Unix()
    fmt.Println(parsedTimestamp) // 1642857600
    
    // UTC时间
    utcTime := time.Date(2022, 1, 22, 8, 0, 0, 0, time.UTC)
    utcTimestamp := utcTime.Unix()
    fmt.Println(utcTimestamp) // 1642857600
    
    // 指定时区
    loc, _ := time.LoadLocation("Asia/Shanghai")
    localTime := time.Date(2022, 1, 22, 16, 0, 0, 0, loc)
    localTimestamp := localTime.Unix()
    fmt.Println(localTimestamp) // 1642857600
}

⚡ C# 时间转时间戳

C# 时间转时间戳
using System;

public class TimeToTimestamp
{
    public static void Main()
    {
        // 获取当前时间戳
        long nowTimestamp = DateTimeOffset.Now.ToUnixTimeSeconds(); // 10位秒级
        Console.WriteLine(nowTimestamp); // 1642857600
        
        long nowTimestampMs = DateTimeOffset.Now.ToUnixTimeMilliseconds(); // 13位毫秒级
        Console.WriteLine(nowTimestampMs); // 1642857600000
        
        // 指定时间转时间戳
        DateTimeOffset dateTime = new DateTimeOffset(2022, 1, 22, 16, 0, 0, TimeSpan.FromHours(8));
        long timestamp = dateTime.ToUnixTimeSeconds();
        Console.WriteLine(timestamp); // 1642857600
        
        // 从DateTime转换
        DateTime dt = new DateTime(2022, 1, 22, 16, 0, 0, DateTimeKind.Local);
        DateTimeOffset dto = new DateTimeOffset(dt);
        long dtTimestamp = dto.ToUnixTimeSeconds();
        Console.WriteLine(dtTimestamp); // 1642857600
        
        // 字符串时间转时间戳
        string timeStr = "2022-01-22 16:00:00";
        DateTime parsedDateTime = DateTime.Parse(timeStr);
        DateTimeOffset parsedDto = new DateTimeOffset(parsedDateTime);
        long parsedTimestamp = parsedDto.ToUnixTimeSeconds();
        Console.WriteLine(parsedTimestamp); // 1642857600
        
        // UTC时间
        DateTime utcDateTime = new DateTime(2022, 1, 22, 8, 0, 0, DateTimeKind.Utc);
        DateTimeOffset utcDto = new DateTimeOffset(utcDateTime);
        long utcTimestamp = utcDto.ToUnixTimeSeconds();
        Console.WriteLine(utcTimestamp); // 1642857600
    }
}

📊 时间转时间戳常用操作对比

语言 获取当前时间戳(秒) 获取当前时间戳(毫秒) 指定时间转时间戳
JavaScript Math.floor(Date.now()/1000) Date.now() new Date(dateStr).getTime()
Python int(time.time()) int(time.time()*1000) int(datetime.timestamp())
Java Instant.now().getEpochSecond() Instant.now().toEpochMilli() localDateTime.toEpochSecond()
PHP time() round(microtime(true)*1000) strtotime(dateStr)
Go time.Now().Unix() time.Now().UnixMilli() time.Parse().Unix()
C# DateTimeOffset.Now.ToUnixTimeSeconds() DateTimeOffset.Now.ToUnixTimeMilliseconds() dateTimeOffset.ToUnixTimeSeconds()

💡 实用提示

🌍

时区处理

转换本地时间时要注意时区设置,确保转换结果的准确性。建议明确指定时区或使用UTC时间。

性能优化

获取当前时间戳时,各语言都有高性能的API,如JavaScript的Date.now()比new Date().getTime()更快。

📏

精度选择

根据业务需求选择合适的精度:一般应用使用秒级时间戳,高精度场景使用毫秒级。

🔄

格式解析

解析字符串时间时,注意格式的一致性,建议使用标准格式或明确指定解析格式。