首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将当前日期转换为整数

将当前日期转换为整数
EN

Stack Overflow用户
提问于 2012-08-22 14:50:39
回答 10查看 263K关注 0票数 44

我想将当前日期转换为整数值。默认情况下,它返回long。当我尝试将long转换为整数,然后将整数值转换为date,这意味着它显示了1970年的日期,

代码语言:javascript
复制
 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));

输出如下:

代码语言:javascript
复制
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位数字)?

EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2012-08-22 14:56:58

问题是Integer不够大,无法存储当前日期,您需要使用Long。

该日期在内部存储为自1970年1月1日以来的毫秒数。

最大整数值为2147483648,而自1970年以来的毫秒数目前约为1345618537869

将最大整数值放入日期中会得到1970年1月26日星期一的结果。

编辑:按照下面的注释显示除以1000的代码:

代码语言:javascript
复制
    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
票数 68
EN

Stack Overflow用户

发布于 2012-08-22 15:13:14

为了获得整数形式的当前日期(10位数字),需要将从new Date().getTime()返回的长整型除以1000。

这将在int范围内,并在2038年1月18日之前有效。

票数 10
EN

Stack Overflow用户

发布于 2014-07-11 02:38:14

如果您只需要一个表示自1970年1月1日以来经过的天数的整数,您可以尝试以下方法:

代码语言:javascript
复制
// 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);
}

较短但可读性较差(稍微快一点?):

代码语言:javascript
复制
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

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12067697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档