Tài nguyên dành cho nhà phát triển & đoạn mã
Tại đây bạn có thể tìm thấy các ví dụ mã để làm việc với dấu thời gian Unix trong các ngôn ngữ lập trình khác nhau. Chọn một ngôn ngữ từ các tùy chọn bên dưới:
Đoạn mã dấu thời gian Unix theo ngôn ngữ
Tại đây bạn có thể tìm thấy các ví dụ mã để làm việc với dấu thời gian Unix trong các ngôn ngữ lập trình khác nhau. Chọn một ngôn ngữ từ các tùy chọn bên dưới:
Công cụ liên quan: Epoch Chuyển đổier, Date Chuyển đổier, Locale Chuyển đổier, Locale Chuyển đổier Guide, Unix ms to Date, Công cụ chuyển đổi múi giờ
Câu hỏi thường gặp
How do I get the current Unix timestamp in JavaScript? Use Math.floor(Date.now() / 1000) for Unix seconds or Date.now() for Unix milliseconds in JavaScript.
How do I convert epoch to datetime in Python, PHP, or SQL? Use the language-specific examples on this page to parse Unix timestamps into UTC or local datetime output for debugging, APIs, and database work.
What is the difference between Unix seconds and Unix milliseconds in code? Unix seconds are usually 10 digits and are common in backend systems. Unix milliseconds are usually 13 digits and are common in JavaScript, analytics, and browser events.
Lấy dấu thời gian hiện tại
// Get current Unix timestamp (seconds)
const timestampInGiây = Math.floor(Date.now() / 1000);
console.log(timestampInGiây);
// Get current Unix timestamp (milliseconds)
const timestampInMili giây = Date.now();
console.log(timestampInMili giây);
Chuyển dấu thời gian sang ngày
// Chuyển đổi Unix timestamp to date
const timestamp = 1609459200; // 2021-01-01 00:00:00 UTC
const date = new Date(timestamp * 1000);
console.log(date.toISOString()); // "2021-01-01T00:00:00.000Z"
console.log(date.toLocaleString()); // Localized format
Chuyển ngày sang dấu thời gian
// Chuyển đổi date string to Unix timestamp
const dateString = '2021-01-01T00:00:00Z';
const timestamp = Math.floor(new Date(dateString).getTime() / 1000);
console.log(timestamp); // 1609459200
// Chuyển đổi Date object to Unix timestamp
const date = new Date(2021, 0, 1); // Lưu ý: tháng start at 0
const timestampFromDate = Math.floor(date.getTime() / 1000);
console.log(timestampFromDate);
Lưu ý:
Date.now() của JavaScript trả về mili giây. Chia cho 1000 để lấy giây.
Khi chuyển từ giây sang đối tượng Date, hãy nhân với 1000.
Lấy dấu thời gian hiện tại
import time
import datetime
# Get current Unix timestamp (seconds)
timestamp_seconds = int(time.time())
print(timestamp_seconds)
# Get current Unix timestamp (milliseconds)
timestamp_milliseconds = int(time.time() * 1000)
print(timestamp_milliseconds)
# Using datetime
dt = datetime.datetime.now()
timestamp_from_datetime = int(dt.timestamp())
print(timestamp_from_datetime)
Chuyển dấu thời gian sang ngày
import time
import datetime
# Chuyển đổi Unix timestamp to date
timestamp = 1609459200 # 2021-01-01 00:00:00 UTC
# Using time module
date_str = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(timestamp))
print(date_str) # '2021-01-01 00:00:00'
# Using datetime module
date_obj = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
print(date_obj.strftime('%Y-%m-%d %H:%M:%S')) # '2021-01-01 00:00:00'
Chuyển ngày sang dấu thời gian
import datetime
# Chuyển đổi date string to Unix timestamp
date_string = '2021-01-01 00:00:00'
date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
# Chuyển đổi to timestamp (assumes local timezone)
timestamp = int(date_obj.timestamp())
print(timestamp)
# Explicitly specify UTC timezone
date_obj_utc = date_obj.replace(tzinfo=datetime.timezone.utc)
timestamp_utc = int(date_obj_utc.timestamp())
print(timestamp_utc)
Lưu ý:
time.time() của Python trả về giây dạng số thực. Dùng int() cho giây nguyên.
Để xử lý múi giờ, hãy cân nhắc dùng thư viện pytz để có hỗ trợ mạnh mẽ hơn.
Lấy dấu thời gian hiện tại
import java.time.Instant;
public class TimestampExample {
public static void main(String[] args) {
// Get current Unix timestamp (seconds)
long timestampInGiây = Instant.now().getEpochSecond();
System.out.println(timestampInGiây);
// Get current Unix timestamp (milliseconds)
long timestampInMili giây = Instant.now().toEpochMilli();
System.out.println(timestampInMili giây);
// Traditional method
long currentTimeMillis = System.currentTimeMillis();
long timestampGiây = currentTimeMillis / 1000L;
System.out.println(timestampGiây);
}
}
Chuyển dấu thời gian sang ngày
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class TimestampToDateExample {
public static void main(String[] args) {
// Chuyển đổi Unix timestamp to date
long timestamp = 1609459200L; // 2021-01-01 00:00:00 UTC
// Using Instant and formatter
Instant instant = Instant.ofEpochSecond(timestamp);
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.of("UTC"));
String formattedDate = formatter.format(instant);
System.out.println(formattedDate); // "2021-01-01 00:00:00"
}
}
Chuyển ngày sang dấu thời gian
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class DateToTimestampExample {
public static void main(String[] args) {
// Chuyển đổi date string to Unix timestamp
String dateString = "2021-01-01 00:00:00";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// Parse and convert to timestamp (assuming UTC)
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter);
ZonedDateTime zonedDateTime = dateTime.atZone(ZoneId.of("UTC"));
long timestamp = zonedDateTime.toEpochSecond();
System.out.println(timestamp); // 1609459200
}
}
Lưu ý:
Java 8+ đã giới thiệu gói java.time với khả năng xử lý ngày/giờ tốt hơn.
Dùng Instant cho dấu thời gian UTC và ZonedDateTime cho các thao tác có nhận biết múi giờ.
Lấy dấu thời gian hiện tại
<?php
// Get current Unix timestamp (seconds)
$timestampInGiây = time();
echo $timestampInGiây;
// Get current Unix timestamp (milliseconds)
$timestampInMili giây = round(microtime(true) * 1000);
echo $timestampInMili giây;
// Using DateTime class
$dateTime = new DateTime();
$timestampFromDateTime = $dateTime->getTimestamp();
echo $timestampFromDateTime;
?>
Chuyển dấu thời gian sang ngày
<?php
// Chuyển đổi Unix timestamp to date
$timestamp = 1609459200; // 2021-01-01 00:00:00 UTC
// Using date function (local timezone)
$dateFormatted = date('Y-m-d H:i:s', $timestamp);
echo $dateFormatted;
// Using gmdate for UTC
$dateFormattedUTC = gmdate('Y-m-d H:i:s', $timestamp);
echo $dateFormattedUTC; // "2021-01-01 00:00:00"
// Using DateTime class
$dateTime = new DateTime("@$timestamp");
$dateTime->setTimezone(new DateTimeZone('UTC'));
echo $dateTime->format('Y-m-d H:i:s');
?>
Chuyển ngày sang dấu thời gian
<?php
// Chuyển đổi date string to Unix timestamp
$dateString = '2021-01-01 00:00:00';
// Using strtotime (assumes local timezone)
$timestamp = strtotime($dateString);
echo $timestamp;
// Specify UTC timezone
$timestampUTC = strtotime($dateString . ' UTC');
echo $timestampUTC;
// Using DateTime class with timezone
$dateTime = new DateTime($dateString, new DateTimeZone('UTC'));
$timestamp = $dateTime->getTimestamp();
echo $timestamp; // 1609459200
?>
Lưu ý:
time() của PHP trả về giây. Dùng microtime(true) cho giây phân số.
Hãy lưu ý cài đặt múi giờ khi dùng các hàm date() và strtotime().
Lấy dấu thời gian hiện tại
package main
import (
"fmt"
"time"
)
func main() {
// Get current Unix timestamp (seconds)
timestampInGiây := time.Now().Unix()
fmt.Println(timestampInGiây)
// Get current Unix timestamp (milliseconds)
// UnixMilli() requires Go 1.17+, using UnixNano() for better compatibility
timestampInMili giây := time.Now().UnixNano() / int64(time.Millisecond)
fmt.Println(timestampInMili giây)
}
Chuyển dấu thời gian sang ngày
package main
import (
"fmt"
"time"
)
func main() {
// Chuyển đổi Unix timestamp to date
timestamp := int64(1609459200) // 2021-01-01 00:00:00 UTC
// Create time object
t := time.Unix(timestamp, 0)
// Format date (UTC)
fmt.Println(t.UTC().Format("2006-01-02 15:04:05"))
// Format date (local timezone)
fmt.Println(t.Format("2006-01-02 15:04:05"))
}
Chuyển ngày sang dấu thời gian
package main
import (
"fmt"
"time"
)
func main() {
// Chuyển đổi date string to Unix timestamp
dateString := "2021-01-01 00:00:00"
// Parse date string (assuming UTC)
// Go uses the reference time "2006-01-02 15:04:05" for time formatting layouts
t, err := time.Parse("2006-01-02 15:04:05", dateString)
if err != nil {
fmt.Println(err)
return
}
// Get Unix timestamp
timestamp := t.Unix()
fmt.Printf("Timestamp: %d\n", timestamp) // 1609459200
}
Lưu ý:
Go sử dụng thời gian tham chiếu "2006-01-02 15:04:05" cho bố cục định dạng thời gian.
Dùng time.Now().Unix() cho giây và time.Now().UnixMilli() cho mili giây (Go 1.17+).
Lấy dấu thời gian hiện tại
using System;
class Program
{
static void Main()
{
// Get current Unix timestamp (seconds)
DateTimeOffset now = DateTimeOffset.UtcNow;
long timestampInGiây = now.ToUnixTimeGiây();
Console.WriteLine(timestampInGiây);
// Get current Unix timestamp (milliseconds)
long timestampInMili giây = now.ToUnixTimeMili giây();
Console.WriteLine(timestampInMili giây);
// Alternative method for older .NET versions
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
TimeSpan timeSpan = DateTime.UtcNow - unixEpoch;
long timestampGiâyAlt = (long)timeSpan.TotalGiây;
Console.WriteLine(timestampGiâyAlt);
}
}
Chuyển dấu thời gian sang ngày
using System;
class Program
{
static void Main()
{
// Chuyển đổi Unix timestamp to date
long timestamp = 1609459200; // 2021-01-01 00:00:00 UTC
// Using DateTimeOffset (.NET Standard 2.0+)
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeGiây(timestamp);
Console.WriteLine(dateTimeOffset.ToString("yyyy-MM-dd HH:mm:ss")); // UTC
// Chuyển đổi to local time
DateTimeOffset localTime = dateTimeOffset.ToLocalTime();
Console.WriteLine(localTime.ToString("yyyy-MM-dd HH:mm:ss")); // Local
}
}
Chuyển ngày sang dấu thời gian
using System;
using System.Globalization;
class Program
{
static void Main()
{
// Chuyển đổi date string to Unix timestamp
string dateString = "2021-01-01 00:00:00";
// Parse date string (assume UTC)
DateTime dateTime = DateTime.ParseExact(
dateString,
"yyyy-MM-dd HH:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
// Chuyển đổi to timestamp
DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime);
long timestamp = dateTimeOffset.ToUnixTimeGiây();
Console.WriteLine($"Timestamp: {timestamp}"); // 1609459200
}
}
Lưu ý:
Dùng DateTimeOffset cho các thao tác dấu thời gian Unix trong .NET Standard 2.0+.
Hãy cẩn thận với DateTimeKind khi làm việc với các đối tượng DateTime.
Lấy dấu thời gian hiện tại
# Get current Unix timestamp (seconds)
timestamp_seconds = Time.now.to_i
puts timestamp_seconds
# Get current Unix timestamp (milliseconds)
timestamp_milliseconds = (Time.now.to_f * 1000).to_i
puts timestamp_milliseconds
# Get current UTC timestamp
require 'time'
utc_timestamp = Time.now.utc.to_i
puts utc_timestamp
Chuyển dấu thời gian sang ngày
require 'time'
# Chuyển đổi Unix timestamp to date
timestamp = 1609459200 # 2021-01-01 00:00:00 UTC
# Create Time object (local timezone)
time = Time.at(timestamp)
puts time.strftime('%Y-%m-%d %H:%M:%S')
# Create UTC Time object
time_utc = Time.at(timestamp).utc
puts time_utc.strftime('%Y-%m-%d %H:%M:%S') # "2021-01-01 00:00:00"
# ISO 8601 format
puts time_utc.iso8601
Chuyển ngày sang dấu thời gian
require 'time'
# Chuyển đổi date string to Unix timestamp
date_string = '2021-01-01 00:00:00'
# Parse date string (local timezone)
time = Time.parse(date_string)
timestamp = time.to_i
puts timestamp
# Parse date string as UTC
time_utc = Time.parse(date_string + ' UTC')
timestamp_utc = time_utc.to_i
puts timestamp_utc # 1609459200
# More precise parsing
require 'date'
datetime = DateTime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
timestamp_from_datetime = datetime.to_time.to_i
puts timestamp_from_datetime
Lưu ý:
Time.now.to_i của Ruby trả về giây. Dùng (Time.now.to_f * 1000).to_i cho mili giây.
Để xử lý múi giờ phức tạp, hãy cân nhắc dùng gem tzinfo.
Lấy dấu thời gian hiện tại
-- MySQL
SELECT UNIX_TIMESTAMP() AS current_timestamp;
SELECT UNIX_TIMESTAMP(NOW(3)) * 1000 AS current_timestamp_ms;
-- PostgreSQL
SELECT EXTRACT(EPOCH FROM NOW()) AS current_timestamp;
SELECT EXTRACT(EPOCH FROM NOW()) * 1000 AS current_timestamp_ms;
-- SQLite
SELECT STRFTIME('%s', 'now') AS current_timestamp;
SELECT STRFTIME('%s', 'now') * 1000 AS current_timestamp_ms;
-- SQL Server
SELECT DATEDIFF(SECOND, '1970-01-01', GETUTCDATE()) AS current_timestamp;
SELECT DATEDIFF(MILLISECOND, '1970-01-01', GETUTCDATE()) AS current_timestamp_ms;
Chuyển dấu thời gian sang ngày
-- MySQL
SELECT FROM_UNIXTIME(1609459200) AS datetime;
SELECT FROM_UNIXTIME(1609459200, '%Y-%m-%d %H:%i:%s') AS formatted_datetime;
-- PostgreSQL
SELECT TO_TIMESTAMP(1609459200) AS datetime;
SELECT TO_CHAR(TO_TIMESTAMP(1609459200), 'YYYY-MM-DD HH24:MI:SS') AS formatted_datetime;
-- SQLite
SELECT DATETIME(1609459200, 'unixepoch') AS datetime;
SELECT STRFTIME('%Y-%m-%d %H:%M:%S', 1609459200, 'unixepoch') AS formatted_datetime;
-- SQL Server
SELECT DATEADD(SECOND, 1609459200, '1970-01-01') AS datetime;
Chuyển ngày sang dấu thời gian
-- MySQL
SELECT UNIX_TIMESTAMP('2021-01-01 00:00:00') AS timestamp;
-- PostgreSQL
SELECT EXTRACT(EPOCH FROM TIMESTAMP '2021-01-01 00:00:00') AS timestamp;
-- SQLite
SELECT STRFTIME('%s', '2021-01-01 00:00:00') AS timestamp;
-- SQL Server
SELECT DATEDIFF(SECOND, '1970-01-01', '2021-01-01 00:00:00') AS timestamp;
Lưu ý:
Các hệ quản trị cơ sở dữ liệu khác nhau có các hàm xử lý dấu thời gian khác nhau.
Luôn cân nhắc ảnh hưởng của múi giờ khi làm việc với dấu thời gian trong cơ sở dữ liệu.
Lấy dấu thời gian hiện tại
' Get current Unix timestamp (seconds)
=INT((NOW()-DATE(1970,1,1))*86400)
' Get current Unix timestamp (milliseconds)
=INT((NOW()-DATE(1970,1,1))*86400*1000)
' Get timestamp for date in cell A1
=INT((A1-DATE(1970,1,1))*86400)
' Account for timezone (subtract 8 hours for UTC+8)
=INT((NOW()-DATE(1970,1,1)-TIME(8,0,0))*86400)
Chuyển dấu thời gian sang ngày
' Chuyển đổi Unix timestamp (seconds) to Excel date
' Assuming A1 contains the timestamp
=DATE(1970,1,1)+A1/86400
' Chuyển đổi Unix timestamp (milliseconds) to Excel date
=DATE(1970,1,1)+A1/86400/1000
' Chuyển đổi to local timezone (add 8 hours for UTC+8)
=DATE(1970,1,1)+A1/86400+TIME(8,0,0)
' Format as text
=TEXT(DATE(1970,1,1)+A1/86400,"yyyy-mm-dd hh:mm:ss")
VBA Functions
' Chuyển đổi Unix timestamp to Excel date
Function UnixToExcelDate(UnixTimestamp As Long) As Date
UnixToExcelDate = DateCộng("s", UnixTimestamp, DateSerial(1970, 1, 1))
End Function
' Chuyển đổi Excel date to Unix timestamp
Function ExcelDateToUnix(ExcelDate As Date) As Long
ExcelDateToUnix = DateDiff("s", DateSerial(1970, 1, 1), ExcelDate)
End Function
' Get current Unix timestamp
Function GetCurrentUnixTimestamp() As Long
GetCurrentUnixTimestamp = DateDiff("s", DateSerial(1970, 1, 1), Now)
End Function
' Usage examples:
' =UnixToExcelDate(1609459200)
' =ExcelDateToUnix(NOW())
' =GetCurrentUnixTimestamp()
Lưu ý:
Excel stores dates as serial numbers, with 1970-01-01 being day 25569 in the 1900 date system.
Always consider timezone conversions when working with timestamps in Excel.
VBA functions provide more flexibility for complex timestamp operations.