Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting the time part of a timestamp in Java

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 will do to achieve the same, but I don't know how to do this in Java.

SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';

like image 776
Vijay Dev Avatar asked Oct 22 '08 18:10

Vijay Dev


People also ask

How do I reset the date in Java?

clear() Calendar. clear(field) Reset the value of field to undefined. field : Required Calendar field, Year, month , date, hour , minute , second , millseconds.

How do I change the date format on a timestamp?

To represent the date-only, use LocalDate class. LocalDate ld = LocalDate. parse( "2019-01-23" ) ; // By default, parses strings in standard ISO 8601 format: YYYY-MM-DD. To capture the current date, specific a time zone.

What is timestamp format in Java?

A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values. The precision of a Timestamp object is calculated to be either: 19 , which is the number of characters in yyyy-mm-dd hh:mm:ss. 20 + s , which is the number of characters in the yyyy-mm-dd hh:mm:ss.


1 Answers

You can go Date->Calendar->set->Date:

Date date = new Date();                      // timestamp now Calendar cal = Calendar.getInstance();       // get calendar instance cal.setTime(date);                           // set cal to date cal.set(Calendar.HOUR_OF_DAY, 0);            // set hour to midnight cal.set(Calendar.MINUTE, 0);                 // set minute in hour cal.set(Calendar.SECOND, 0);                 // set second in minute cal.set(Calendar.MILLISECOND, 0);            // set millis in second Date zeroedDate = cal.getTime();             // actually computes the new Date 

I love Java dates.

Note that if you're using actual java.sql.Timestamps, they have an extra nanos field. Calendar of course, knows nothing of nanos so will blindly ignore it and effectively drop it when creating the zeroedDate at the end, which you could then use to create a new Timetamp object.

I should also note that Calendar is not thread-safe, so don't go thinking you can make that a static single cal instance called from multiple threads to avoid creating new Calendar instances.

like image 148
Alex Miller Avatar answered Sep 21 '22 17:09

Alex Miller