各语言获取/转换Unix时间戳示例
各语言的示例代码(PHP、JavaScript、Python、Java、MySQL)由豆包自动生成,仅供参考,大家使用时请注意核查!切记!!!
PHP
$timestamp_s = time();
$timestamp_ms = round(microtime(true) * 1000);
function timestamp_to_beijing($timestamp) {
if (strlen((string)$timestamp) == 13) {
$timestamp = $timestamp / 1000;
}
date_default_timezone_set('Asia/Shanghai');
return date('Y-m-d H:i:s', $timestamp);
}
function beijing_to_timestamp($datetime_str) {
date_default_timezone_set('Asia/Shanghai');
return strtotime($datetime_str);
}
JavaScript
const timestampMs = Date.now();
const timestampS = Math.floor(Date.now() / 1000);
function formatTime(timestamp) {
if (timestamp.toString().length === 10) {
timestamp = timestamp * 1000;
}
const date = new Date(timestamp);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
const seconds = String(date.getSeconds()).padStart(2, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
Python
timestamp_s = int(time.time())
timestamp_ms = int(time.time() * 1000)
def timestamp_to_beijing(timestamp):
if len(str(timestamp)) == 13:
timestamp = timestamp / 1000
beijing_tz = timezone(timedelta(hours=8))
beijing_time = datetime.fromtimestamp(timestamp, tz=beijing_tz)
return beijing_time.strftime("%Y-%m-%d %H:%M:%S")
def beijing_to_timestamp(datetime_str):
beijing_tz = timezone(timedelta(hours=8))
dt = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S").replace(tzinfo=beijing_tz)
return int(dt.timestamp())
Java
public class TimestampUtils {
public static long getCurrentTimestampMs() {
return System.currentTimeMillis();
}
public static long getCurrentTimestampS() {
return System.currentTimeMillis() / 1000;
}
public static String timestampToBeijing(long timestamp) {
if (String.valueOf(timestamp).length() == 10) {
timestamp = timestamp * 1000;
}
ZoneId beijingZone = ZoneId.of("Asia/Shanghai");
LocalDateTime beijingTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(timestamp), beijingZone
);
return beijingTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
}
public static long beijingToTimestamp(String datetimeStr) {
ZoneId beijingZone = ZoneId.of("Asia/Shanghai");
LocalDateTime localDateTime = LocalDateTime.parse(
datetimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
);
ZonedDateTime zonedDateTime = localDateTime.atZone(beijingZone);
return zonedDateTime.toEpochSecond();
}
}
MySQL
SELECT UNIX_TIMESTAMP();
SELECT UNIX_TIMESTAMP() * 1000;
SELECT FROM_UNIXTIME(1735689600, '%Y-%m-%d %H:%i:%s') AS beijing_time;
SELECT UNIX_TIMESTAMP('2025-01-01 12:00:00') AS timestamp;
SET time_zone = '+8:00';