我正在尝试从数据库中获取时间戳值,将它们转换为日历,然后再转换回时间戳,但会失去精度。
以下是复现问题的代码:
import java.sql.Timestamp;
import java.util.Calendar;
public class Test {
public static void main(String[] args)
{
Timestamp timestamp = new Timestamp(112, 10, 5, 15, 39, 11, 801000000);
System.out.println("BEFORE "+timestamp.toString());
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp.getTime());
timestamp = new Timestamp(calendar.getTimeInMillis());
System.out.println("AFTER "+timestamp.toString());
}
}
这是转换的示例结果
BEFORE 2012-10-18 14:30:13.362001
AFTER 2012-10-18 14:30:13.362
它失去了精确度。 我应该怎么做才能保持小数的值不变?
Calendar calendar = Calendar.getInstance(); Timestamp timestamp = new Timestamp(new Date().getTime()); System.out.println("1 -> "+timestamp); // Thread.currentThread().sleep(1000); calendar.setTimeInMillis(timestamp.getTime()); timestamp = new Timestamp(calendar.getTimeInMillis()); System.out.println("2 -> "+timestamp);
- Subhrajyoti Majumder