Unix时间戳转换有很多种方法,其中最直接的就是在线转换时间戳,当然,我们更愿意自己转换时间戳,以熟练掌握这项操作,下文分享的Unix时间戳代码便是编写好的转换方式,可根据实际情况直接复制修改使用。
Unix时间戳转换普通时间的方法:
1、各种编程语言获取当前Unix时间戳方法:
JavatimeJavaScriptMath.round(new Date().getTime()/1000)getTime()返回数值的单位是毫秒Microsoft .NET / C#epoch = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000MySQLSELECT unix_timestamp(now())PerltimePHPtime()PostgreSQLSELECT extract(epoch FROM now())Python先 import time 然后 time.time()Ruby获取Unix时间戳:Time.now 或 Time.new显示Unix时间戳:Time.now.to_iSQL ServerSELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())Unix / Linuxdate +%sVBScript / ASPDateDiff("s", "01/01/1970 00:00:00", Now())其他操作系统(如果Perl被安装在系统中)命令行状态:perl -e "print time"2、各种编程语言中实现Unix时间戳转化为普通时间方法:
JavaString date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date(Unix timestamp * 1000))JavaScript先 var unixTimestamp = new Date(Unix timestamp * 1000) 然后 commonTime = unixTimestamp.toLocaleString()Linuxdate -d @Unix timestampMySQLfrom_unixtime(Unix timestamp)Perl先 my $time = Unix timestamp 然后 my ($sec, $min, $hour, $day, $month, $year) = (localtime($time))[0,1,2,3,4,5,6]PHPdate('r', Unix timestamp)PostgreSQLSELECT TIMESTAMP WITH TIME ZONE 'epoch' + Unix timestamp) * INTERVAL '1 second';Python先 import time 然后 time.gmtime(Unix timestamp)RubyTime.at(Unix timestamp)SQL ServerDATEADD(s, Unix timestamp, '1970-01-01 00:00:00')VBScript / ASPDateAdd("s", Unix timestamp, "01/01/1970 00:00:00")其他操作系统(如果Perl被安装在系统中)命令行状态:perl -e "print scalar(localtime(Unix timestamp))"3、各种编程语言中实现普通时间转换为Unix时间戳方法:
Javalong epoch = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse("01/01/1970 01:00:00");JavaScriptvar commonTime = new Date(Date.UTC(year, month - 1, day, hour, minute, second))MySQLSELECT unix_timestamp(time)时间格式: YYYY-MM-DD HH:MM:SS 或 YYMMDD 或 YYYYMMDDPerl先 use Time::Local 然后 my $time = timelocal($sec, $min, $hour, $day, $month, $year);PHPmktime(hour, minute, second, day, month, year)PostgreSQLSELECT extract(epoch FROM date('YYYY-MM-DD HH:MM:SS'));Python先 import time 然后 int(time.mktime(time.strptime('YYYY-MM-DD HH:MM:SS', '%Y-%m-%d %H:%M:%S')))RubyTime.local(year, month, day, hour, minute, second)SQL ServerSELECT DATEDIFF(s, '1970-01-01 00:00:00', time)Unix / Linuxdate +%s -d"Jan 1, 1970 00:00:01"VBScript / ASPDateDiff("s", "01/01/1970 00:00:00", time)以上内容便是Unix时间戳转换普通时间的方法分享,如果用户不理解转换概念,可以使用这些代码来转换时间戳,精确到秒。