Resetting the time part of a timestamp in Java

后端 未结 10 1225
慢半拍i
慢半拍i 2020-12-04 23:56

In Java, given a timestamp, how to reset the time part alone to 00:00:00 so that the timestamp represents the midnight of that particular day ?

In T-SQL, this query

10条回答
  •  盖世英雄少女心
    2020-12-05 00:41

    Using Calendar.set() would certanly be "by the book" solution, but you might also use java.sql.Date:

    java.util.Date originalDate = new java.util.Date();
    java.sql.Date wantedDate = new java.sql.Date(originalDate.getTime());
    

    That would do exactly what you want since:

    To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

    Since java.sql.Date extends java.util.Date, you can freely use it as such. Be aware that wantedDate.getTime() will retrieve original timestamp though - that's why you don't want to create another java.util.Date from java.sql.Date!

提交回复
热议问题