有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从java中的int值获取日期对象

我有一个int值,我想从int值中获得该Date值的int对象

例如:

 int value = 166368;
 long l = (long)value;
 Date date = new Date(l);

Value是我想要Date对象作为这个特定值的整数值

现在我想获得这个int值的Date。我尝试将这个int值转换为long,然后在Date对象中设置long值,但它没有返回正确的值

那么如何实现这一点呢


共 (4) 个答案

  1. # 1 楼答案

    如果你检查API public Date(long date)是这样做的

    Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

    166368不到3分钟,所以日期不会改变。如果你打印出来,你只会发现时间上的不同

    也许你正试图做这样的事情

    Date now = new Date();
    long nowLong = now.getTime();
    long newLong = nowLong + 166368;
    System.out.println(new Date(newLong).toString());
    

    使用DateFormat类是处理日期的好方法

    DateFormat df=新的简化格式(“日/月/年”); 字符串formattedDate=df。格式(新日期())

    有一篇详细的文章here

  2. # 2 楼答案

    正如@ggreiner所指出的,你应该告诉我们,你希望从int值166368得到哪个日期

    您的问题“从java中的int值获取日期对象”是可能的:

    final int x = Integer.MAX_VALUE;
    final Date d = new Date(x);
    final Date today = new Date();
    System.out.println("max integer x:" + x);
    System.out.println("the Max date could be represented by x:" + d);
    System.out.println("today in number:" + today.getTime());
    

    运行上面的代码,你会得到:

    max integer x:2147483647 
    the Max date could be represented by x:Sun Jan 25 21:31:23 CET 1970 
    today in number:1330362276028
    

    这意味着,如果您将integer传递给Date()构造函数,它可以工作,但您不会得到晚于Sun Jan 25 21:31:23 CET 1970的日期

  3. # 3 楼答案

    如果您传递的长值是自历元(1970年1月1日)起的毫秒,并且166368毫秒=166.3秒<;3分钟,我想你应该得到1970年1月1日作为日期值。对吗

  4. # 4 楼答案

    传递给日期构造函数的值必须是自1970年1月1日00:00:00.000 GMT以来经过的毫秒数

    您的代码是正确的,但是您在这里传递的值似乎太小而不正确