Utviklerressurser og kodesnutter
Her finner du kodeeksempler for arbeid med Unix-tidsstempler i ulike programmeringsspråk. Velg et språk nedenfor:
Unix-tidsstempelutdrag etter språk
Her finner du kodeeksempler for arbeid med Unix-tidsstempler i ulike programmeringsspråk. Velg et språk nedenfor:
Relaterte verktøy: Epoch Konverterer, Date Konverterer, Locale Konverterer, Locale Konverterer Guide, Unix ms to Date, Tidssonekonverterer
Ofte stilte spørsmål
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.
Hent gjeldende tidsstempel
// Get current Unix timestamp (seconds)
const timestampInSekunder = Math.floor(Date.now() / 1000);
console.log(timestampInSekunder);
// Get current Unix timestamp (milliseconds)
const timestampInMillisekunder = Date.now();
console.log(timestampInMillisekunder);
Konverter tidsstempel til dato
// Konverter 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
Konverter dato til tidsstempel
// Konverter 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
// Konverter Date object to Unix timestamp
const date = new Date(2021, 0, 1); // Merk: måneder start at 0
const timestampFromDate = Math.floor(date.getTime() / 1000);
console.log(timestampFromDate);
Merk:
Date.now() i JavaScript returnerer millisekunder. Del på 1000 for sekunder.
Når du konverterer fra sekunder til et Date-objekt, må du gange med 1000.
Hent gjeldende tidsstempel
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)
Konverter tidsstempel til dato
import time
import datetime
# Konverter 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'
Konverter dato til tidsstempel
import datetime
# Konverter 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')
# Konverter 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)
Merk:
time.time() i Python returnerer sekunder som flyttall. Bruk int() for hele sekunder.
For håndtering av tidssoner bør du vurdere å bruke pytz-biblioteket for mer robust støtte.
Hent gjeldende tidsstempel
import java.time.Instant;
public class TimestampExample {
public static void main(String[] args) {
// Get current Unix timestamp (seconds)
long timestampInSekunder = Instant.now().getEpochSecond();
System.out.println(timestampInSekunder);
// Get current Unix timestamp (milliseconds)
long timestampInMillisekunder = Instant.now().toEpochMilli();
System.out.println(timestampInMillisekunder);
// Traditional method
long currentTimeMillis = System.currentTimeMillis();
long timestampSekunder = currentTimeMillis / 1000L;
System.out.println(timestampSekunder);
}
}
Konverter tidsstempel til dato
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class TimestampToDateExample {
public static void main(String[] args) {
// Konverter 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"
}
}
Konverter dato til tidsstempel
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) {
// Konverter 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
}
}
Merk:
Java 8+ introduserte pakken java.time med bedre håndtering av dato og tid.
Bruk Instant for UTC-tidsstempler og ZonedDateTime for tidssonebevisste operasjoner.
Hent gjeldende tidsstempel
<?php
// Get current Unix timestamp (seconds)
$timestampInSekunder = time();
echo $timestampInSekunder;
// Get current Unix timestamp (milliseconds)
$timestampInMillisekunder = round(microtime(true) * 1000);
echo $timestampInMillisekunder;
// Using DateTime class
$dateTime = new DateTime();
$timestampFromDateTime = $dateTime->getTimestamp();
echo $timestampFromDateTime;
?>
Konverter tidsstempel til dato
<?php
// Konverter 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');
?>
Konverter dato til tidsstempel
<?php
// Konverter 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
?>
Merk:
time() i PHP returnerer sekunder. Bruk microtime(true) for brøkdelssekunder.
Vær oppmerksom på tidssoneinnstillinger når du bruker funksjonene date() og strtotime().
Hent gjeldende tidsstempel
package main
import (
"fmt"
"time"
)
func main() {
// Get current Unix timestamp (seconds)
timestampInSekunder := time.Now().Unix()
fmt.Println(timestampInSekunder)
// Get current Unix timestamp (milliseconds)
// UnixMilli() requires Go 1.17+, using UnixNano() for better compatibility
timestampInMillisekunder := time.Now().UnixNano() / int64(time.Millisecond)
fmt.Println(timestampInMillisekunder)
}
Konverter tidsstempel til dato
package main
import (
"fmt"
"time"
)
func main() {
// Konverter 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"))
}
Konverter dato til tidsstempel
package main
import (
"fmt"
"time"
)
func main() {
// Konverter 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
}
Merk:
Go bruker referansetiden "2006-01-02 15:04:05" for oppsett av tidsformatering.
Bruk time.Now().Unix() for sekunder og time.Now().UnixMilli() for millisekunder (Go 1.17+).
Hent gjeldende tidsstempel
using System;
class Program
{
static void Main()
{
// Get current Unix timestamp (seconds)
DateTimeOffset now = DateTimeOffset.UtcNow;
long timestampInSekunder = now.ToUnixTimeSekunder();
Console.WriteLine(timestampInSekunder);
// Get current Unix timestamp (milliseconds)
long timestampInMillisekunder = now.ToUnixTimeMillisekunder();
Console.WriteLine(timestampInMillisekunder);
// Alternative method for older .NET versions
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
TimeSpan timeSpan = DateTime.UtcNow - unixEpoch;
long timestampSekunderAlt = (long)timeSpan.TotalSekunder;
Console.WriteLine(timestampSekunderAlt);
}
}
Konverter tidsstempel til dato
using System;
class Program
{
static void Main()
{
// Konverter Unix timestamp to date
long timestamp = 1609459200; // 2021-01-01 00:00:00 UTC
// Using DateTimeOffset (.NET Standard 2.0+)
DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSekunder(timestamp);
Console.WriteLine(dateTimeOffset.ToString("yyyy-MM-dd HH:mm:ss")); // UTC
// Konverter to local time
DateTimeOffset localTime = dateTimeOffset.ToLocalTime();
Console.WriteLine(localTime.ToString("yyyy-MM-dd HH:mm:ss")); // Local
}
}
Konverter dato til tidsstempel
using System;
using System.Globalization;
class Program
{
static void Main()
{
// Konverter 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);
// Konverter to timestamp
DateTimeOffset dateTimeOffset = new DateTimeOffset(dateTime);
long timestamp = dateTimeOffset.ToUnixTimeSekunder();
Console.WriteLine($"Timestamp: {timestamp}"); // 1609459200
}
}
Merk:
Bruk DateTimeOffset for Unix-tidsstempeloperasjoner i .NET Standard 2.0+.
Vær forsiktig med DateTimeKind når du arbeider med DateTime-objekter.
Hent gjeldende tidsstempel
# 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
Konverter tidsstempel til dato
require 'time'
# Konverter 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
Konverter dato til tidsstempel
require 'time'
# Konverter 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
Merk:
Time.now.to_i i Ruby returnerer sekunder. Bruk (Time.now.to_f * 1000).to_i for millisekunder.
For kompleks håndtering av tidssoner kan du vurdere å bruke gem-en tzinfo.
Hent gjeldende tidsstempel
-- 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;
Konverter tidsstempel til dato
-- 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;
Konverter dato til tidsstempel
-- 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;
Merk:
Ulike databasesystemer har ulike funksjoner for håndtering av tidsstempler.
Vurder alltid tidssonekonsekvenser når du arbeider med tidsstempler i databaser.
Hent gjeldende tidsstempel
' 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)
Konverter tidsstempel til dato
' Konverter Unix timestamp (seconds) to Excel date
' Assuming A1 contains the timestamp
=DATE(1970,1,1)+A1/86400
' Konverter Unix timestamp (milliseconds) to Excel date
=DATE(1970,1,1)+A1/86400/1000
' Konverter 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
' Konverter Unix timestamp to Excel date
Function UnixToExcelDate(UnixTimestamp As Long) As Date
UnixToExcelDate = DateLegg til("s", UnixTimestamp, DateSerial(1970, 1, 1))
End Function
' Konverter 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()
Merk:
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.