Why does a date conversion return different timestamps?

wdmv1981 :

I am converting a GregorianCalendar instance to a Date to get a unix timestamp.

But I was wondering why the same date returns different Unix timestamps each time.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

Calendar calendar = new GregorianCalendar();
calendar.set(2018, 0, 1, 0,0,0);
System.out.println(sdf.format(calendar.getTime()));
Date date = calendar.getTime();

System.out.println(sdf.format(date));
System.out.println(date.getTime());

The date itself is correct and is always the same, "2018/01/01 00:00:00". But why is the unix timestamp different each time? For example, these are the values after 5 executions.

1514761200624
1514761200618
1514761200797
1514761200209
1514761200132
achAmháin :

I am assuming you are instantiating everything within a loop in your example?

If so, you are not setting the milliseconds difference, so they change (however slightly) in each iteration of the loop.

To avoid this, you could either set the milliseconds, or do the instantiation outside of the loop:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar calendar = new GregorianCalendar();
calendar.set(2018, 0, 1, 0, 0, 0);
for (int i = 0; i < 5; i++) {
     System.out.println(sdf.format(calendar.getTime()));
     Date date = calendar.getTime();
     System.out.println(sdf.format(date));
     System.out.println(date.getTime());
}

This will produce:

2018/01/01 00:00:00

2018/01/01 00:00:00

1514764800128

2018/01/01 00:00:00

2018/01/01 00:00:00

1514764800128

2018/01/01 00:00:00

2018/01/01 00:00:00

1514764800128

2018/01/01 00:00:00

2018/01/01 00:00:00

1514764800128

2018/01/01 00:00:00

2018/01/01 00:00:00

1514764800128

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=308745&siteId=1