Unix时间戳是指从1970年1月1日(UTC/GMT的午夜)开始所经过的秒数,不考虑闰秒。它是一种用于计算机系统中记录时间的方式,可以用于表示某个特定时刻的绝对时间。Unix时间戳在很多计算机系统和编程语言中被广泛使用,包括Unix、Linux、Java等。它以一个32位或64位的整数的形式来存储,而不是普通的日期和时间格式。在软件开发中,Unix时间戳能够有效缩减程序的体积,只要一个整数形式就可以表示时间。
需要注意的是,Unix时间戳有其局限性,例如32位Unix时间戳会在2038年遇到所谓的“2038年问题”或“Y2038”,届时其最大值将被达到,之后将从零开始计算,导致时间戳溢出。因此,现代系统多采用64位Unix时间戳以避免此类问题。
以下是一些常见编程语言中获取当前 Unix 时间戳的代码示例:
import time;
timestamp = int(time.time())
const timestamp = Math.round(Date.now() / 1000);
long timestamp = System.currentTimeMillis() / 1000;
#include <chrono>;
#include <ctime>;
auto now = std::chrono::system_clock::now();
std::time_t timestamp = std::chrono::system_clock::to_time_t(now);
long timestamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;
$timestamp = time();
timestamp = Time.now.to_i
import "time";
timestamp := time.Now().Unix()
use std::time;
let timestamp = time::SystemTime::now().duration_since(time::UNIX_EPOCH).unwrap().as_secs();
let timestamp = Int(Date().timeIntervalSince1970)
以下是一些常见编程语言中将Unix时间戳转换为字符串(通常为可读的日期和时间格式)的代码示例:
import time
timestamp = 1626739200 # 示例Unix时间戳
formatted_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
print(formatted_time)
const timestamp = 1626739200; // 示例Unix时间戳
const formattedTime = new Date(timestamp * 1000).toISOString().slice(0, 19).replace('T', ' ');
console.log(formattedTime);
long timestamp = 1626739200L; // 示例Unix时间戳
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getDefault());
String formattedTime = sdf.format(new Date(timestamp * 1000));
System.out.println(formattedTime);
#include <iostream>
#include <ctime>
#include <iomanip>
#include <sstream>
int main() {
time_t timestamp = 1626739200; // 示例Unix时间戳
std::tm* localTime = std::localtime(×tamp);
std::ostringstream oss;
oss << std::put_time(localTime, "%Y-%m-%d %H:%M:%S");
std::string formattedTime = oss.str();
std::cout << formattedTime << std::endl;
return 0;
}
using System;
class Program {
static void Main() {
long timestamp = 1626739200; // 示例Unix时间戳
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(timestamp);
string formattedTime = dateTime.ToString("yyyy-MM-dd HH:mm:ss");
Console.WriteLine(formattedTime);
}
}
$timestamp = 1626739200; // 示例Unix时间戳
$formattedTime = date('Y-m-d H:i:s', $timestamp);
echo $formattedTime;
timestamp = 1626739200 # 示例Unix时间戳
formatted_time = Time.at(timestamp).strftime('%Y-%m-%d %H:%M:%S')
puts formatted_time
package main
import (
"fmt"
"time"
)
func main() {
timestamp := int64(1626739200) // 示例Unix时间戳
t := time.Unix(timestamp, 0)
formattedTime := t.Format("2006-01-02 15:04:05")
fmt.Println(formattedTime)
}
use std::time;
fn main() {
let timestamp = 1626739200; // 示例Unix时间戳
let dt = time::Unix(timestamp);
let formatted_time = dt.format("%Y-%m-%d %H:%M:%S").to_string();
println!("{}", formatted_time);
}
let timestamp = 1626739200 // 示例Unix时间戳
let date = Date(timeIntervalSince1970: TimeInterval(timestamp))
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
formatter.timeZone = TimeZone.current
let formattedTime = formatter.string(from: date)
print(formattedTime)
以下是一些常见编程语言中将日期时间字符串转换为Unix时间戳的代码示例:
from datetime import datetime
date_string = "2021-07-20 12:34:56" # 示例日期时间字符串
date_format = "%Y-%m-%d %H:%M:%S"
timestamp = int(datetime.strptime(date_string, date_format).timestamp())
print(timestamp)
const dateString = "2021-07-20T12:34:56"; // 示例日期时间字符串,注意ISO格式
const timestamp = new Date(dateString).getTime() / 1000;
console.log(timestamp);
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) {
String dateString = "2021-07-20 12:34:56"; // 示例日期时间字符串
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date date = sdf.parse(dateString);
long timestamp = date.getTime() / 1000;
System.out.println(timestamp);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
#include <iostream>
#include <ctime>
#include <sstream>
#include <iomanip>
int main() {
std::string dateString = "2021-07-20 12:34:56"; // 示例日期时间字符串
std::istringstream iss(dateString);
std::tm tm{};
iss >> std::get_time(&tm, "%Y-%m-%d %H:%M:%S");
std::time_t timestamp = std::mktime(&tm);
std::cout << timestamp << std::endl;
return 0;
}
using System;
using System.Globalization;
class Program {
static void Main() {
string dateString = "2021-07-20 12:34:56"; // 示例日期时间字符串
DateTime date = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
long timestamp = (long)date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Console.WriteLine(timestamp);
}
}
$dateString = "2021-07-20 12:34:56"; // 示例日期时间字符串
$timestamp = strtotime($dateString);
echo $timestamp;
date_string = "2021-07-20 12:34:56" # 示例日期时间字符串
timestamp = DateTime.parse(date_string).to_time.to_i
puts timestamp
package main
import (
"fmt"
"time"
)
func main() {
dateString := "2021-07-20 12:34:56" // 示例日期时间字符串
layout := "2006-01-02 15:04:05"
t, err := time.Parse(layout, dateString)
if err != nil {
panic(err)
}
timestamp := t.Unix()
fmt.Println(timestamp)
}
use std::time;
use chrono::DateTime;
use chrono::NaiveDateTime;
use chrono::Utc;
fn main() {
let date_string = "2021-07-20 12:34:56".to_string(); // 示例日期时间字符串
let dt = DateTime::<Utc>::parse_from_str(&date_string, "%Y-%m-%d %H:%M:%S").unwrap();
let timestamp = dt.with_time_zone(&Utc).timestamp();
println!("{}", timestamp);
}