我想将当前日期转换为整数值。默认情况下,它返回long。当我尝试将long转换为整数,然后将整数值转换为date,这意味着它显示了1970年的日期,
int i = (int) new Date().getTime();
System.out.println("Integer : " + i);
System.out.println("Long : "+ new Date().getTime());
System.out.println("Long date : " + new Date(new Date().getTime()));
System.out.println("Int Date : " + new Date(i));
输出如下:
Integer : 1292838124
Long : 1345617601771
Long date : Wed Aug 22 12:10:01 IST 2012
Int Date : Fri Jan 16 04:37:18 IST 1970
谁能帮帮我,如何将当前日期转换为整数(10位数字)?
发布于 2012-08-22 14:56:58
问题是Integer不够大,无法存储当前日期,您需要使用Long。
该日期在内部存储为自1970年1月1日以来的毫秒数。
最大整数值为2147483648,而自1970年以来的毫秒数目前约为1345618537869
将最大整数值放入日期中会得到1970年1月26日星期一的结果。
编辑:按照下面的注释显示除以1000的代码:
int i = (int) (new Date().getTime()/1000);
System.out.println("Integer : " + i);
System.out.println("Long : "+ new Date().getTime());
System.out.println("Long date : " + new Date(new Date().getTime()));
System.out.println("Int Date : " + new Date(((long)i)*1000L));
Integer : 1345619256
Long : 1345619256308
Long date : Wed Aug 22 16:37:36 CST 2012
Int Date : Wed Aug 22 16:37:36 CST 2012
发布于 2012-08-22 15:13:14
为了获得整数形式的当前日期(10位数字),需要将从new Date().getTime()返回的长整型除以1000。
这将在int范围内,并在2038年1月18日之前有效。
发布于 2014-07-11 02:38:14
如果您只需要一个表示自1970年1月1日以来经过的天数的整数,您可以尝试以下方法:
// magic number=
// millisec * sec * min * hours
// 1000 * 60 * 60 * 24 = 86400000
public static final long MAGIC=86400000L;
public int DateToDays (Date date){
// convert a date to an integer and back again
long currentTime=date.getTime();
currentTime=currentTime/MAGIC;
return (int) currentTime;
}
public Date DaysToDate(int days) {
// convert integer back again to a date
long currentTime=(long) days*MAGIC;
return new Date(currentTime);
}
较短但可读性较差(稍微快一点?):
public static final long MAGIC=86400000L;
public int DateToDays (Date date){
return (int) (date.getTime()/MAGIC);
}
public Date DaysToDate(int days) {
return new Date((long) days*MAGIC);
}
希望这能有所帮助。
编辑:这可能会持续到周五7月11日01:00:00 CET 5881580
https://stackoverflow.com/questions/12067697
复制相似问题