源程序如下:
public class TimeTool {
//2011/08/17 12:01:12.984851 1313554656851 1313554657851 1313583456851
public static void main(String[] args) {
TimeTool time=new TimeTool();
String timeStamp=null;
String date=null;
timeStamp = time.Date2Stamp("2011/08/17 12:01:13.984851");
System.out.println("原时间为="+timeStamp);
System.out.println("转换的时间戳为="+timeStamp);
date=time.Stamp2Date(timeStamp);
System.out.println("转换后的时间="+date);
}
public static String Date2Stamp(String date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SS");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("CEST")); //设置时区
Date d = null;
try {
d = simpleDateFormat.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long ts = d.getTime();
return String.valueOf(ts);
}
/**
* 将时间戳转换为日期
* @param stamp 时间戳
* @return 时间,返回格式为 yyyy-MM-dd-HH-mm-ss
*/
public static String Stamp2Date(String stamp){
String res;
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SS");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("CEST")); //设置时区
long lt=new Long(Long.parseLong(stamp));
Date date=new Date(lt);
res=simpleDateFormat.format(date);
return res;
}
}
输出结果:
原时间为=1313583457851
转换的时间戳为=1313583457851
转换后的时间=2011/08/17 12:17:37.851
对于毫秒,SimpleDateFormat应该只能精确到毫秒三位,比如2011/08/17 12:01:13.984这个字符串是可以正常转换的
但是2011/08/17 12:01:13.984851这个字符串的最后三位851是没办法正常转化的,至于为什么差了几分钟,个人猜测可能是
SimpleDateFormat这个类使用了一些位运算导致的。
说白了就是精度不够的问题
这个问题你自己用debug调试看看吧说不定在Date date=new Date(lt); 这里时间就不一样了,不一定是SimpleDateFormat这个的问题,自己调试一切清楚