是否可以将System.currentTimeMillis转换为Date

时间:2012-12-17 21:01:56

标签: java

我在Mongo DB中有一个名为updated_at

的字段

将以这种方式查看数据库

updated_at:NumberLong(“1355754242785”)

此Updated_at字段以数据库的方式创建

long now = System.currentTimeMillis();

从其中一个DB Record中,我的值为

updated_at" : NumberLong("1355754242785"), "volatility12" : "na", "vwap" : "0", "wk52hi" : "0", "wk52hidate" : "----"}

例如说它的值是1355754242785

是否可以转换1355754242785,当它被更新?

当我尝试转换时

public class Aim {
    public static void main(String[] args) {
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss.SSS");
        long now = 1355754242785; // Error here saying out of range 
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(now);
        System.out.println(now + " = " + formatter.format(calendar.getTime()));
    }
}

3 个答案:

答案 0 :(得分:5)

更改

  long now = 1355754242785; // Error here saying out of range 

long now = 1355754242785L; 

这是一个编译错误,用于分配;这应该会让你知道问题与日期无关,只是假设Java中的文字数字是int,其最大值为2^31-1。您必须添加L后缀以告知Java该文字将被解释为long

答案 1 :(得分:3)

当然,只需使用Date(long)构造函数,它以毫秒为单位接收时间作为参数。做这样的事情:

Date date = new Date(System.currentTimeMillis());

顺便提一句,相当于简单地写下这个:

Date date = new Date();

答案 2 :(得分:1)

long now = 1355754242785L;
Date nowAsDate = new Date(now);