Java Date cut off time information

231,473

Solution 1

The recommended way to do date/time manipulation is to use a Calendar object:

Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();

Solution 2

Have you looked at the DateUtils truncate method in Apache Commons Lang?

Date truncatedDate = DateUtils.truncate(new Date(), Calendar.DATE);

will remove the time element.

Solution 3

Just a quick update in light of the java.time classes now built into Java 8 and later.

LocalDateTime has a truncatedTo method that effectively addresses what you are talking about here:

LocalDateTime.now().truncatedTo(ChronoUnit.MINUTES)

This will express the current time down to minutes only:

2015-03-05T11:47

You may use a ChronoUnit (or a TemporalUnit) smaller than DAYS to execute the truncation (as the truncation is applied only to the time part of LocalDateTime, not to the date part).

Solution 4

Have you looked at Joda ? It's a much easier and more intuitive way to work with dates and times. For instance you can convert trivially between (say) LocalDateTime and LocalDate objects.

e.g. (to illustrate the API)

LocalDate date = new LocalDateTime(milliseconds).toLocalDate()

Additionally it solves some thread-safety issues with date/time formatters and is to be strongly recommended for working with any date/time issues in Java.

Solution 5

Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
Share:
231,473
Marco
Author by

Marco

Updated on August 31, 2020

Comments

  • Marco
    Marco over 3 years

    I have a Java Date object containing date and time information. I want to write a method that cuts off the time information, truncates the hours-minutes-seconds, so I only have the date left.

    Example input:

    2008-01-01 13:15:00
    

    Expected output:

    2008-01-01 00:00:00
    

    Do you have a tip? I tried doing something like this:

    (timestamp / (24 * 60 * 60 * 1000)) * (24 * 60 * 60 * 1000)
    

    but I ran into problems with the timezone.

  • Brian Agnew
    Brian Agnew over 14 years
    I believe it does. It's a recommendation to use a better library rather than battle with the broken java.util classes (as evidenced by the question)
  • Joel
    Joel over 14 years
    Of course it relates, Joda is THE library for date,time & calendar manipulation in Java. It would be a dereliction of duty not to recommend it.
  • Brian Agnew
    Brian Agnew over 14 years
    I confess I was faintly surprised not to find anyone else mentioning it. Thanks for emphasising that.
  • Mark Bennett
    Mark Bennett over 12 years
    The thread safety issue is very interesting, I found this post researching an Oracle/Hibernate error "IllegalArgumentException, sun.util.calendar.ZoneInfo.getOffset(ZoneInfo), oracle.jdbc.driver.DateCommonBinder.zoneOffset(OraclePrepare‌​dStatement)". This talks about another Oracle problems only appearing w heavy load forums.oracle.com/forums/thread.jspa?threadID=325576 It's really hard to even create an object with invalid milliseconds in normal code. For me, I think I'll downcast in my thread using Joda, rather than let Oracle use the possibly-suspect non-joda stuff.
  • Prem
    Prem about 12 years
    @cletus, Is it possible to remove the time from Date object. I want pure date like 2008-01-01 no time portion.
  • Arcao
    Arcao almost 11 years
    This doesn't work, because calendar.clear(Calendar.HOUR_OF_DAY); doesn't clear hours. The solution from @cletus works OK.
  • m190
    m190 almost 11 years
    Sorry, you are right, I corrected it, for hours you should set the value. In general it almost the same way how to truncate date...
  • Ryan
    Ryan over 10 years
    I wish I could downvote everybody who up-voted this. Who are all these people who +1 a reply that doesn't even attempt to answer the question? An answer using Joda would be more than welcome, but this isn't it...
  • Stan
    Stan over 10 years
    There is an tiny error in this code - the left bracket in not placed correctly, it must be timestamp -= timestamp % (24 * 60 * 60 * 1000). This will cut off the time part. And Im sure this way is more sufficient than creating Caledar object and playing with its methods or even using any other 3rd party libraries
  • Ogre Psalm33
    Ogre Psalm33 over 10 years
    Updated link again (come on Apache! Quit movin your docs around!)
  • Basil Bourque
    Basil Bourque almost 10 years
    I would not say java.util.Calendar is recommended. Sun/Oracle supplanted that class in Java 8 with the new java.time package. Use either that or Joda-Time.
  • Basil Bourque
    Basil Bourque almost 10 years
    The midnight-related methods and classes in Joda-Time are now deprecated. The developers recommend against using them. Instead use the method withTimeAtStartOfDay.
  • Basil Bourque
    Basil Bourque almost 10 years
    @Ryan How is this answer not relevant? The Question asked for the date without a time-of-day. This answer presents a class whose sole purpose is representing a date without a time-of-day.
  • Ryan
    Ryan almost 10 years
    At first I was thinking I was just being a frustrated prick until I thought about it. The poster asked about modifying a Java java.util.Date object. The resultant object in this answer is not a Date nor can it be (effortlessly) used in a Date. Date has time fields, LocalDate does not. I probably literally needed '00:00:00' like in the question.
  • Basil Bourque
    Basil Bourque almost 10 years
    @Ryan As I mentioned in my answer, the question is not clear. Does the person want (a) no time-of-day as suggested by title, or (b) does the person want first moment of the day ("midnight") as suggested by the example 00:00:00? My supposition, like Brian Agnew, is that the person asking wants a date-only with no time-of-day but with only java.util.Date as a frame of reference does not know how to ask otherwise. Before Java 8, there is no built-in way to truly represent date-only. LocalDate in Joda-Time & java.time is a legitimate solution.
  • Basil Bourque
    Basil Bourque almost 10 years
    [A] Your answer is redundant. Already posted by Brian Agnew. [B] Your code is incorrect, as it ignores time zone, the very issue raised in the question.
  • lamusique
    lamusique almost 10 years
    Could be redundant but I just put a simpler example here because I recognized an answer shouldn't be in comments. Yes, java.util.Date ignores TimeZone but the original question was with a Java Date object thus I used java.util.Date. Moreover it doesn't explain how his timezone is problematic with java.util.Date (when? where?) although he can't help using other than Date.
  • Clint Eastwood
    Clint Eastwood over 9 years
    This is the definitive answer (assuming that one can and wants to use Joda Time)
  • Alexander Taylor
    Alexander Taylor over 9 years
    keywords: java.time, Java 8, LocalDateTime.truncatedTo()
  • h7r
    h7r over 9 years
    Thank you for pointing out. Updated the answer to consider this.
  • assylias
    assylias almost 9 years
    You can only use ChronoUnits up to DAYS - higher units will throw an exception.
  • Cloud
    Cloud over 8 years
    Minus of this approach that timezone in what truncate operation is performed is always local PC timezone. So if you working with calendar and dates in UTC timezone or in any timezone other than local timezone - it could truncate date not as intended.
  • Charles Wood
    Charles Wood over 8 years
    You can also use toLocalDate to get an object that doesn't even have a time component.
  • Wim Deblauwe
    Wim Deblauwe over 8 years
    Calendar is no longer recommended. See stackoverflow.com/a/28868089/40064 if you are using Java 8.
  • Drew
    Drew about 8 years
    No, this is NOT the correct solution, BEWARE. This is the same as rounding the date value to floor, that is - you may get 28 March for timestamp of 29 March (in your locale). So Calendar-based solutions (Apache's DateUtils uses Calendar, too) is the only way
  • Basil Bourque
    Basil Bourque almost 8 years
    The java.sql.Date class pretends to represent a date-only value but actually does have a time-of-day adjusted for UTC time zone. So not really a fit solution to the Question.
  • Basil Bourque
    Basil Bourque almost 8 years
    This answer only produces dates for the context of UTC time zone.
  • Alexandru Severin
    Alexandru Severin over 7 years
    This will also not work when the time changes due to Daylight saving time.
  • Basil Bourque
    Basil Bourque over 6 years
    FYI, the troublesome old date-time classes such as java.util.Calendar are now legacy, supplanted by the java.time classes. See Tutorial by Oracle.
  • Jaroslav Záruba
    Jaroslav Záruba over 6 years
    as @Cloud pointed out, the fact that i don't see the Calendar instance here (have no control over it) makes me a bit nervous :)
  • Basil Bourque
    Basil Bourque over 6 years
    FYI, this Answer uses troublesome old date-time classes supplanted years ago by the java.time classes.
  • Basil Bourque
    Basil Bourque about 6 years
    The troublesome Calendar and Date classes became legacy years ago with the java.time classes implementing JSR 310 in Java 8 and later. Suggesting their use in 2018 is poor advice.
  • Basil Bourque
    Basil Bourque about 6 years
    FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
  • Basil Bourque
    Basil Bourque about 6 years
    FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. See Tutorial by Oracle.
  • Pino
    Pino over 5 years
    That method is surprisingly long and had at least two bugfixes.
  • epox
    epox almost 4 years
    This will truncate in local TimeZone, not in UTC that Date (getTime) represents.
  • PlexQ
    PlexQ about 3 years
    This answer is irrelevant. If you're trying to manipulate dates dealing with JDBC information, you don't have the choice of using JodaTime really. JDBC STILL uses java.util.Date, despite it being horribly broken.
  • Brian Agnew
    Brian Agnew about 3 years
    @PlexQ no mention of JDBC in the question, I’m afraid
  • Chad Lehman
    Chad Lehman about 3 years
    I like simple, elegant solutions like this one. With Calendar, you have to make 6 different api calls. When your application is always, always only ever going to run in one time zone--because it is deployed on a server and it is for the State government--you can feel pretty safe that you won't have problems with timezone.