Resetting the time part of a timestamp in Java

后端 未结 10 1223
慢半拍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:30

    Assuming your "timestamp" is a java.util.Date, which is represented as the number of milliseconds since the beginning of the epoch (Jan 1, 1970), you can perform the following arithmetic:

    public static Date stripTimePortion(Date timestamp) {
        long msInDay = 1000 * 60 * 60 * 24; // Number of milliseconds in a day
        long msPortion = timestamp.getTime() % msInDay;
        return new Date(timestamp.getTime() - msPortion);
    }
    

提交回复
热议问题