当前位置: 移动技术网 > IT编程>开发语言>Java > java_时间戳与Date_相互转化的实现代码

java_时间戳与Date_相互转化的实现代码

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

1、时间戳的定义

时间戳是指文件属性里的创建、修改、访问时间。

数字时间戳技术是数字签名技术一种变种的应用。在电子商务交易文件中,时间是十分重要的信息。在书面合同中,文件签署的日期和签名一样均是十分重要的防止文件被伪造和篡改的关键性内容。数字时间戳服务(dts:digital time stamp service)是网上电子商务安全服务项目之一,能提供电子文件的日期和时间信息的安全保护。

时间戳(time-stamp)是一个经加密后形成的凭证文档,它包括三个部分:  

  1. 需加时间戳的文件的摘要(digest);  
  2. dts收到文件的日期和时间;  
  3. dts的数字签名。  

一般来说,时间戳产生的过程为:用户首先将需要加时间戳的文件用hash编码加密形成摘要,然后将该摘要发送到dts,dts在加入了收到文件摘要的日期和时间信息后再对该文件加密(数字签名),然后送回用户。  

书面签署文件的时间是由签署人自己写上的,而数字时间戳则不然,它是由认证单位dts来加的,以dts收到文件的时间为依据。

2、时间戳转化为date(or string)

//时间戳转化为sting或date 
  simpledateformat format = newsimpledateformat("yyyy-mm-dd hh:mm:ss"); 
  long time=newlong(445555555); 
  string d = format.format(time); 
  date date=format.parse(d); 
  system.out.println("format to string(date):"+d); 
  system.out.println("format to date:"+date); 
  运行结果:
    format to string(date):1970-01-06 11:45:55
format to date:tue jan 06 11:45:55 cst 1970

3、date(or string)转化为时间戳

//date或者string转化为时间戳 
  simpledateformat format = newsimpledateformat("yyyy-mm-dd hh:mm:ss"); 
  string time="1970-01-06 11:45:55"; 
  date date = format.parse(time); 
  system.out.print("format to times:"+date.gettime());

运行结果:

format to times:445555000

4、注意

定义simpledateformat时newsimpledateformat("yyyy-mm-dd hh:mm:ss");里面字符串头尾不能有空格,有空格那是用转换时对应的时间空格也要有空格(两者是对应的),比如:

 //date或者string转化为时间戳 
   simpledateformat format = newsimpledateformat(" yyyy-mm-dd hh:mm:ss "); 
   string time="1970-01-06 11:45:55"; 
   date date = format.parse(time); 
   system.out.print("format to times:"+date.gettime()); 

运行结果(报错):

exception in thread "main"java.text.parseexception: unparseable date: "1970-01-06 11:45:55"

改正:

 //date或者string转化为时间戳
simpledateformat format = newsimpledateformat(" yyyy-mm-dd hh:mm:ss "); 
string time=" 1970-01-06 11:45:55 ";//注:改正后这里前后也加了空格 
date date = format.parse(time); 
system.out.print("format to times:"+date.gettime()); 
 运行结果:
  format to times:445555000

一、java中date类中的gettime()是获取时间戳的,java中生成的时间戳精确到毫秒级别,而unix中精确到秒级别,所以通过java生成的时间戳需要除以1000。

二、下面是java代码

import java.text.parseexception; 
import java.text.simpledateformat; 
import java.util.date; 
 
public class baidu { 
 
/** 
* @param args 
*/ 
public static void main(string[] args) { 
try { 
string time = "2011/07/29 14:50:11"; 
date date = new simpledateformat("yyyy/mm/dd hh:mm:ss").parse(time); 
long unixtimestamp = date.gettime()/1000; 
system.out.println(unixtimestamp); 
} catch (parseexception e) { 
e.printstacktrace(); 
} 
} 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

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

相关文章:

验证码:
移动技术网