简体   繁体   中英

Obtain Date object from the int value in java

I have a int value and from int value I want to obtain Date object for that int value.

Example:

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

Value is my integer value for which I want Date object for this particular value.

Now I want to obtain Date for this int value. I try to convert this int value to long and then set the long value in Date object but it not return correct value.

So how to achieve this?

The value that you pass to the Date constructor needs to be the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

Your code is correct, but the value that you are passing in here seems much too small to be correct.

If the long value you pass is milliseconds since the epoch (1-Jan-1970), and 166368 ms = 166.3 seconds < 3 min, I'd say that you should be getting 1-Jan-1970 as the Date value. Correct?

as @ggreiner pointed out, you should tell us, which date are you expecting to get from int value 166368?

your question "Obtain Date object from the int value in java" is possible:

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());

run the above code, you got:

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

which means, if you pass integer to Date() constructor, it works, but you won't get Date later than Sun Jan 25 21:31:23 CET 1970 .

If you check the API public Date(long date) does this

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 is hardly 3 minutes, So the date is not going to change. If you print you will find a difference only in time.

May be you are trying to do something like this

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

Neat way to play with dates would be to use DateFormat class.

DateFormat df = new SimpleDateFormat("dd/MM/yy"); String formattedDate = df.format(new Date());

There is a detailed article here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM