当前位置: 移动技术网 > IT编程>开发语言>Java > java中如何获取时间戳的方法实例

java中如何获取时间戳的方法实例

2019年07月19日  | 移动技术网IT编程  | 我要评论

前言

数字时间戳技术是数字签名技术一种变种的应用。是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至现在的总秒数(引用自百度百科)

在java开发过程中经常会遇到统计某一天或是某一个月的数据,因此常常需要获取截取数据的两个时间戳(比如统计今天的数据,则需要获取一个开始时间为今天零点以及一个结束时间为明天零点),然后根据数据相关的时间是否在该时间区间内来判断是否将其计入统计数据中。

一、java获取时间戳

话不多说,首先我们先拿上面的例子说起吧。如何获取今天零点以及明天零点的两个时间戳。

public long gettoday(){
  datetime now = new datetime();
  return new datetime(now.getyear(), now.getmonthofyear(), now.getdayofmonth(), 0, 0, 0, 0).getmillis();
 }
 
 public long gettomorrow(){
  datetime now = new datetime();
  return new datetime(now.getyear(), now.getmonthofyear(), now.getdayofmonth(), 0, 0, 0, 0).plusdays(1).getmillis();
 }

上面的方法中用到了datetime中的plusdays(),同理,你如果需要获取下 个星期(年,月,时,分,秒,毫秒)前的时间戳,都有同样的plusyears(int x),plusmonths(int x)等等与之对应,如果要获取今天之前的就把传入一个负整数参数即可。

然而很多时候我们需要某个特定时间的时间戳,比如这个月5号14点23分6秒138毫秒的时间戳(这个时间并没有特殊的含义,随便选的)。

public long gettime(){
  long now = new date().gettime();
  calendar calendar = calendar.getinstance();
  calendar.settimeinmillis(now);
  calendar.set(calendar.day_of_month, 5);
  calendar.set(calendar.hour, 14);
  calendar.set(calendar.minute, 23);
  calendar.set(calendar.second, 6);
  calendar.set(calendar.millisecond, 138);
  return calendar.gettimeinmillis();
 }

再比如我们可能需要知道这个星期二的10点10分10秒的时间戳。

public long gettime(){
  long now = new date().gettime();
  calendar calendar = calendar.getinstance();
  calendar.settimeinmillis(now);
  calendar.set(calendar.day_of_week, 2);
  calendar.set(calendar.hour, 10);
  calendar.set(calendar.minute, 10);
  calendar.set(calendar.second, 10);
  return calendar.gettimeinmillis();
 }

二、java中两种获取精确到秒的时间戳的方法

java中的时间戳的毫秒主要通过最后的三位来进行计量的,下面给大家分享从网上整理的两种不同的方式将最后三位去掉。

方法一:通过string.substring()方法将最后的三位去掉

/** 
* 获取精确到秒的时间戳 
* @return 
*/ 
public static int getsecondtimestamp(date date){ 
if (null == date) { 
return 0; 
} 
string timestamp = string.valueof(date.gettime()); 
int length = timestamp.length(); 
if (length > 3) { 
return integer.valueof(timestamp.substring(0,length-3)); 
} else { 
return 0; 
} 
} 

方法二:通过整除将最后的三位去掉

/** 
* 获取精确到秒的时间戳 
* @param date 
* @return 
*/ 
public static int getsecondtimestamptwo(date date){ 
if (null == date) { 
return 0; 
} 
string timestamp = string.valueof(date.gettime()/1000); 
return integer.valueof(timestamp); 
}

以上就是我总结的一些获取时间戳的方法,如果平时需要快速进行时间与时间戳之间的转换,也可以在站长工具得到快速解决:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网