Code snippets by language A-Z
In the examples on this page, 1800000000 is used as an example epoch time. Replace it with your own value to convert it.
Current programming languages, OSes and databases
- AutoIT routines
- C routines
- C# routines
- C++11 routines
- Dart routines
- Delphi routines
- Erlang/OTP routines
- Go routines
- Google BigQuery routines
- Groovy/Jenkins routines
- Java routines
- JavaScript routines
- Lua routines
- macOS commands
- MATLAB routines
- Microsoft Excel / LibreOffice Calc
- MySQL queries
- Objective-C routines
- Oracle PL/SQL routines
- Perl routines
- PHP routines
- PostgreSQL routines
- PowerShell routines
- Python routines
- R routines
- Ruby routines
- Rust routines
- SQL Server routines
- SQLite routines
- Tcl/Tk routines
- Unix/Linux Shell (Bash) commands
Legacy / EOL
- Adobe ColdFusion routines
- ASP / VBScript routines
- Crystal Reports routines
- IBM Informix routines
- IBM PureData System for Analytics routines
- Solaris (OS commands)
- Visual FoxPro routines
AutoIT routines
Get current epoch (seconds):
_DateDiff('s', "1970/01/01 00:00:00", _NowCalc())
Convert human-readable date to epoch:
_DateDiff('s', "1970/01/01 00:00:00", "YYYY/MM/DD HH:MM:SS")
Convert epoch to human-readable date:
_DateAdd("s", $EpochSeconds , "1970/01/01 00:00:00")
C# routines
Get current epoch (seconds):
DateTimeOffset.Now.ToUnixTimeSeconds()
(.NET Framework 4.6+/.NET Core).
Older versions:
var epoch = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
Convert epoch to human-readable date:
private string epoch2string(int epoch) {
return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch).ToShortDateString(); }
C++ routines
Get current epoch (seconds):
auto now = std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
Dart routines
Get current epoch:
DateTime.now().millisecondsSinceEpoch ~/ 1000
In microseconds:
DateTime.now().microsecondsSinceEpoch
Convert epoch to human-readable date:
DateTime.fromMillisecondsSinceEpoch(1800000000*1000)
Delphi routines
Get current epoch (seconds):
Epoch := DateTimeToUnix(Now, False);
There is also a DateTimeToMillisecondsSince1970 function.
Convert human-readable date to epoch:
Epoch := DateTimeToUnix(StrToDateTime(myString));
Convert epoch to human-readable date:
myString := DateTimeToStr(UnixToDateTime(Epoch));
Where Epoch is a signed integer.
Erlang/OTP routines
Get current epoch (seconds):
erlang:system_time(seconds).
Go routines
package main
import (
"fmt"
"time"
)
func main() {
// Current epoch time
fmt.Printf("Current epoch time is:\t\t\t%d\n\n", currentEpochTime())
// Convert from human-readable date to epoch
humanReadable := time.Now()
fmt.Printf("Human-readable time is:\t\t\t%s\n", humanReadable)
fmt.Printf("Human-readable to epoch time is:\t%d\n\n", humanReadableToEpoch(humanReadable))
// Convert from epoch to human-readable date
epoch := currentEpochTime()
fmt.Printf("Epoch to human-readable time is:\t%s\n", epochToHumanReadable(epoch))
}
func currentEpochTime() int64 {
return time.Now().Unix()
// time.Now().UnixMilli() for milliseconds
}
func humanReadableToEpoch(date time.Time) int64 {
return date.Unix()
}
func epochToHumanReadable(epoch int64) time.Time {
return time.Unix(epoch, 0)
}
Google BigQuery routines
Get current epoch (seconds):
SELECT UNIX_SECONDS(CURRENT_TIMESTAMP()) AS unix_seconds;
Change to UNIX_MILLIS(CURRENT_TIMESTAMP()) for milliseconds.
Convert epoch to human-readable date:
SELECT TIMESTAMP_SECONDS(event_time.seconds) as readable_time
FROM `your_project.dataset.table`;
Groovy/Jenkins routines
Get current epoch (seconds):
System.currentTimeMillis() / 1000
Convert epoch to human-readable date:
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter
long unixTimestamp = 1800000000L
def instant = Instant.ofEpochSecond(unixTimestamp)
def formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss")
.withZone(ZoneId.of("Europe/London"))
println "Readable date: ${formatter.format(instant)}"
Java routines
Get current epoch (seconds):
long epoch = System.currentTimeMillis()/1000;
Convert human-readable date to epoch:
long epoch = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("01/01/1970 01:00:00").getTime() / 1000;
Timestamp in seconds, remove '/1000' for milliseconds.
Convert epoch to human-readable date:
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date(epoch*1000));
Epoch in seconds, remove '*1000' for milliseconds.
JavaScript routines
Get current epoch (seconds):
Math.floor(new Date().getTime()/1000.0)
Convert an epoch to human-readable date:
Example with epoch date '1800000000':var myDate = new Date(1800000000*1000);
document.write("UTC: "+myDate.toUTCString()+"<br>Local: "+myDate.toLocaleString());
The example above gives the following output (with epoch date 123):
Convert human-readable dates to epoch:var myDate = new Date("July 1, 2030 02:30:00"); // Your timezone!
var myEpoch = myDate.getTime()/1000.0;
document.write(myEpoch);
The example above gives the following output:
There are many ways to create dates in JavaScript (for example with setFullYear, setMonth, setDay, etc.).
Lua routines
Get current epoch (seconds):
epoch = os.time()
Convert epoch to human-readable date:
datestring = os.date('%c',1800000000)
macOS command
Get current epoch (seconds):
date -j
Convert epoch to human-readable date:
date -j -r 1800000000
MATLAB routines
Convert epoch to human-readable date:
datestr(719529+TimeInSeconds/86400,'dd-mmm-yyyy HH:MM:SS')
Microsoft Excel / LibreOffice Calc
Convert epoch to human-readable date:
=(A1 / 86400) + 25569
Format the result cell for date/time, the result will be in GMT time
A1 is the cell with the epoch number.
For other time zones:
=((A1 +/- [time zone adjustment]) / 86400) + 25569
Find the time zone adjustment in seconds for your local time on the time zones list page.
Objective-C routines
Get current epoch (seconds):
[[NSDate date] timeIntervalSince1970];
Returns a double. To get a string:
NSString *currentTimestamp = [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
Convert epoch to human-readable date:
NSDate * myDate = [NSDate dateWithTimeIntervalSince1970:1800000000]; NSLog(@"%@", date);
Oracle PL/SQL routines
Get current epoch (seconds):
SELECT (CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS DATE) - TO_DATE('01/01/1970','DD/MM/YYYY')) * 24 * 60 * 60 FROM DUAL;
Convert epoch to human-readable date:
SELECT to_date('01-JAN-1970','dd-mon-yyyy')+(1800000000/60/60/24) from dual
Replace 1526357743 with epoch.
PostgreSQL routines
Get current epoch (seconds):
SELECT extract(epoch FROM now());
Convert human-readable date to epoch:
SELECT extract(epoch FROM date('2000-01-01 12:34'));
With timestamp:
SELECT EXTRACT(EPOCH FROM TIMESTAMP WITH TIME ZONE '2018-02-16 20:38:40-08');
With interval:
SELECT EXTRACT(EPOCH FROM INTERVAL '5 days 3 hours');
Convert epoch to human-readable date:
PostgreSQL version 8.1 and higher:
SELECT to_timestamp(1800000000);
Older versions:
SELECT TIMESTAMP WITH TIME ZONE 'epoch' + 1800000000 * INTERVAL '1 second';
PowerShell routines
Get current epoch (seconds):
[DateTimeOffset]::Now.ToUnixTimeSeconds()
or:
[int][double]::Parse((Get-Date (get-date).touniversaltime() -UFormat %s))
Convert epoch to human-readable date:
PowerShell 5.1+ (Windows 10+):
[DateTimeOffset]::FromUnixTimeSeconds(1800000000).LocalDateTime
PowerShell Core (7.0+):
Get-Date -UnixTimeSeconds 1800000000
Version for all Windows PowerShell versions:
Function get-epochDate ($epochDate) {
[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($epochDate)) }
get-epochDate 1800000000
Python routines
Get current epoch (seconds):
import time;
time.time()
Convert human-readable date to epoch:
import calendar, time;
calendar.timegm(time.strptime('2000-01-01 12:34:00', '%Y-%m-%d %H:%M:%S'))
Convert epoch to human-readable date:
import time; time.ctime(1800000000)
Or:
import time;
time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(1800000000))
Replace time.localtime with time.gmtime for GMT time. Or using datetime:
import datetime;
datetime.datetime.utcfromtimestamp(epoch).replace(tzinfo=datetime.timezone.utc)
R routines
Get current epoch (seconds):
as.numeric(Sys.time())
Convert human-readable date to epoch:
as.numeric(as.POSIXct("YYYY-MM-dd HH:mm:ss", tz = "GMT", origin="1970-01-01"))
The origin parameter is optional.
Convert epoch to human-readable date:
as.POSIXct(epoch, origin="1970-01-01", tz="GMT")
Ruby routines
Get current epoch (seconds):
Time.now
(or Time.new). To display the epoch: Time.now.to_i
Convert human-readable date to epoch:
Time.local(year, month, day, hour, minute, second, usec)
(or Time.gm for GMT/UTC input). To display add .to_i
Convert epoch to human-readable date:
Time.at(epoch)
Rust routines
Get current epoch / convert human-readable date to epoch:
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
SQL Server routines
Get current epoch (seconds):
SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE());
Convert human-readable date to epoch:
SELECT DATEDIFF(s, '1970-01-01 00:00:00', 'time_field')
Convert epoch to human-readable date:
SELECT DATEADD(s, 1800000000, '1970-01-01 00:00:00');
Replace s with ms if the epoch is in milliseconds.
SQLite routines
Get current epoch (seconds):
SELECT unixepoch();
SELECT strftime('%s', 'now');
Convert human-readable date to epoch:
SELECT strftime('%s', 'timestring');
Convert epoch to human-readable date:
SELECT datetime(1800000000, 'unixepoch');
Or local time zone:
SELECT datetime(1800000000, 'unixepoch', 'localtime');
Tcl/Tk routines
Get current epoch (seconds):
clock seconds
Convert epoch to human-readable date:
clock format 1800000000
See Tcl/Tk clock documentation for more details.
Unix/Linux Shell (Bash) commands
Get current epoch (seconds):
date +%s
Convert human-readable date to epoch:
date +%s -d"Jan 1, 1980 00:00:01"
Replace '-d' with '-ud' to input in GMT/UTC time.
Convert epoch to human-readable date:
date -d @1800000000
Replace 1800000000 with your epoch, needs recent version of 'date'. Replace '-d' with '-ud' for GMT/UTC time.
Legacy / EOL
Adobe ColdFusion routines
Get current epoch (seconds):
<cfset epochTime = left(getTickcount(), 10)>
Convert human-readable date to epoch:
int(parseDateTime(datetime).getTime()/1000);
Convert epoch to human-readable date:
DateAdd("s",epoch,"1/1/1970");
ASP / VBScript routines
Warning! You need to correct the time zone for these examples to work.
A manual quick fix is to either:
- look up the offset in wmi and add it to Now()
- change the "01/01/1970 00:00:00" string, for example for GMT/UTC+1 = "01/01/1970 01:00:00"
The current Unix time:
' check time zone
DateDiff("s", "01/01/1970 00:00:00", Now())
Current Unix time with time zone fix:
function date2epoch(myDate)
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate (myDate)
DateDiff("s", "01/01/1970 00:00:00", CDate(dateTime.GetVarDate (false)))
end function
Wscript.echo date2epoch(Now())
date2epoch converts a VBScript date to a Unix timestamp:
' check time zone if your date is not GMT/UTC
function date2epoch(myDate)
date2epoch = DateDiff("s", "01/01/1970 00:00:00", myDate)
end function
Usage example:
date2epoch(Now())
epoch2date converts Unix timestamps back to VBScript dates:
' result is GMT/UTC
function epoch2date(myEpoch)
epoch2date = DateAdd("s", myEpoch, "01/01/1970 00:00:00")
end function
Crystal Reports routines
Convert epoch to human-readable date:
DateAdd("s", {EpochTimeStampField}-14400, #1/1/1970 00:00:00#)
-14400 used for Eastern Standard Time. See Time Zones.
IBM Informix routines
Get current epoch (seconds):
SELECT dbinfo('utc_current') FROM sysmaster:sysdual;
Convert epoch to human-readable date:
SELECT dbinfo('utc_to_datetime',1800000000) FROM sysmaster:sysdual;
IBM PureData System for Analytics routines
Convert epoch to human-readable date:
select 996673954::int4::abstime::timestamp;
Solaris (OS commands)
Get current epoch (seconds):
/usr/bin/nawk 'BEGIN {print srand()}'
Solaris doesn't support date +%s, but the default seed value for nawk's random-number generator is the number of seconds since the epoch.
Visual FoxPro routines
Get current epoch (seconds):
DATETIME() - {^1970/01/01 00:00:00}
Warning: time zones may not be handled correctly by Visual FoxPro.
Thanks to everyone who sent corrections and updates!