认识Unix时间戳

以前只知道各种语言是用时间戳(timestamp)这个抽象的东西管理时间的,比如Python、JavaScript,内置的时间类生存对象后都是以方法将时间戳格式化成可供阅读的时间的。但具体谈到时间戳究竟是什么?还真没有去了解过。

时间戳,称为Unix时间戳(Unix timestamp),或称Unix Time,或Posix time。从格林威治时间(GMT)的1970年1月1日00时00分00秒开始到现在的毫秒数,北京时间是从1970年1月1日08时00分00秒开始。这个时间是Unix系统发布的时间。

Java中System中的静态方法currentTimeMillis方法返回时间戳。
先来看下jdk文档中的定义:

currentTimeMillis

public static long currentTimeMillis()

Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).

Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
See Also:
Date

我们发现这个静态方法返回的是一个长整型,因此这样使用:

long timestamp = System.ccurrentTimeMillis();

写过一些库比较全面的语言的人肯定会想到他们的Date对象中有类似getFullYear, getDay, getHour……之类的方法。但是有时候我们直接使用时间戳做做除法、求余就可以算出来的。

得到总秒数:
totalSecond = totalMilliseconds / 1000

得到当前是多少秒
currentSecond = totalSecond % 60

得到总的分钟数:
totalMinutes = currentSecond / 60

得到当前的分钟:
currentMinutes = totalMinutes % 60

得到总的小时:
totalHours = totalMinutes / 60

得到当前的小时
currentHours = totalHours % 24

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值