标签云

微信群

扫码加入我们

WeChat QR Code

Continuing from Stack Overflow question Java program to get the current date without timestamp:

What is the most efficient way to get a Date object without the time? Is there any other way than these two?

// Method 1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateWithoutTime = sdf.parse(sdf.format(new Date()));

// Method 2
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
dateWithoutTime = cal.getTime();

Update:

  1. I knew about Joda-Time; I am just trying to avoid additional library for such a simple (I think) task. But based on the answers so far Joda-Time seems extremely popular, so I might consider it.

  2. By efficient, I mean I want to avoid temporary object String creation as used by method 1, meanwhile method 2 seems like a hack instead of a solution.


Efficient? Do you need more efficiency than what's provided e.g., by method1?

2018年08月15日23分52秒

What do you mean by "efficient"? A date is basically a typed long, you can't really do this in less memory than that. If you mean "convenient", JODA time is the way to go.

2018年08月16日23分52秒

+1 Exactly the question I had.

2018年08月16日23分52秒

I like method 2. Create a static method in an utility class and just use it. I've been this approach for years.

2018年08月15日23分52秒

Nitpicking on your "update 1": if it was "such a simple task", I guess Sun wouldn't have come to such horrendous and inefficient API, and you (and a lot of other people) wouldn't be asking that question at all ;-)

2018年08月16日23分52秒

In enterprise applications we don't always have the option to add/use other libraries. I appreciate the pointer to Joda Time, but it's really not an answer to the original issue of getting the date portion using the standard Java. Thanks. Upvoting Chathuranga's answer.

2018年08月16日23分52秒

noogrub: Chathugranga's answer doesn't answer the original question, which is asking about how to get a Date object - that answer formats a date to a string, which isn't the same thing. Fundamentally, asking what date a Date is on is a meaningless question without more information: the time zone and the calendar system you're using.

2018年08月16日23分52秒

"In enterprise applications we don't always have the option to add/use other libraries". Really ? Are you suggesting you can't use 3rd party libs at all ?

2018年08月16日23分52秒

BrianAgnew noogrub's comment seems to be related to non-tech constraints, I think

2018年08月16日23分52秒

From today's perspective: "Joda-Time is the de facto standard date and time library for Java prior to Java SE 8. Users are now asked to migrate to java.time (JSR-310)."

2018年08月15日23分52秒

In what way is this different from the already proposed "method 1" in the original question?

2018年08月16日23分52秒

Does not address what timezone this occurs in (left to arbitrary default timezone of JVM).

2018年08月16日23分52秒

If you're going to add a new library, let it be Joda instead of Apache Commons.

2018年08月16日23分52秒

+1 Dibbeke The difference is not just that you would be adding one library instead of another. Sometimes one doesn't want to learn a whole new library just for the trivial task of truncating the time from a date. Or doesn't want to have code that mixes Date / Calendar with Joda dates using sometimes the former and sometimes the latter. Or cannot afford / justify replacing all the well-working Date / Calendar -based code with another library for such a trivial purpose. While suggesting Joda is certainly good as it is clearly superior and simply The Right Thing, sometimes real life kicks in.

2018年08月16日23分52秒

Genius! Helped me alot

2018年08月15日23分52秒

Thanks for mentioning time zone. It had not occurred to me that "what day it is" isn't an absolute concept.

2018年08月16日23分52秒

ToolmakerSteve Getting the date always involves a time zone. But the trick is that if you fail to specify a time zone, your JVM’s current default time zone is automatically applied in determining the date. On top of that, the JVM’s current default time zone can change at any moment! Any code in any thread of any app within the JVM can call TimeZone.setDefault during runtime and immediately affect all other code running in that JVM. Moral of the Story: Always specify a time zone.

2018年08月15日23分52秒

For me, this is currently: "Sat Feb 19 01:00:00 CET 2011". If you want to use that, then only with UTC.

2018年08月16日23分52秒

Isn't line 3 long dateOnly = (currentTime / millisInDay) * millisInDay; the same as writing long dateOnly = currentTime; ?

2018年08月16日23分52秒

It's not, because of integer math. Think of it more like Math.floor(currentTime / millisInDay) * millisInDay. He's effectively setting the time to 00:00:00 that way.

2018年08月16日23分52秒

This solution is probably fine for most application, but be warned the assumption that a day has 60 * 60 * 24 * 1000 is not always true. You can for instance have leap seconds in some days.

2018年08月16日23分52秒

This is arguably the most obtuse and not recommended way over other 1 and 2-line clear and concise methods.

2018年08月16日23分52秒

The new java.time package in Java 8 also offers a LocalDate class similar to Joda-Time.

2018年08月16日23分52秒

Ideally you would pass a DateTimeZone to that LocalDate constructor. Determining the current date depends on time zone, as Paris begins a new date earlier than Montréal. If you omit the time zone, your JVM's default time zone is applied. Usually better to specify than rely on default.

2018年08月16日23分52秒

Note: Those approaches saying "the date at midnight" does not handle daylight savings time and multiple timezones well.

2018年08月16日23分52秒

I confirm it, I was incrementing dates by one day in my app, and learned about this with a bug report from users in a timezone with DST (my country does not use DST). In the day DST begins my app adds 11 hours instead of 12. Perhaps using noon as the hour for a "no time" date is better?

2018年08月16日23分52秒

Jose_GD It is at best still a hack. You might find youtube.com/watch?v=-5wpm-gesOY entertaining.

2018年08月16日23分52秒

Thorbjorn, you're right, just wanted to avoid JodaTime because adding a library for just one feature sound overkill for me. I knew about that video, funny indeed.

2018年08月16日23分52秒

Jose_GD The point was that there is an actual real life use case that in which your approach would be considered a bug. If you found one, there might be more... I do not know how Joda handles this, but you could have a look. Also note that Java 8 brings a new date-time library (based on the experiences with Joda) which you may want to look into.

2018年08月16日23分52秒

This answer fails to address the question. Obtaining a formatted string was not the goal.

2018年08月16日23分52秒

I don't think this is i18n friendly

2018年08月16日23分52秒

The Question asked for no time-of-day. Your result is a date-time object which does indeed have a time-of-day, that time being 00:00:00 usually (may vary by time zone for anomalies such as DST). So, as other Answers note, the LocalDate class is more appropriate, from Joda-Time (assuming you are referencing Joda-Time – which you should be noting explicitly when citing classes not bundled with Java).

2018年08月16日23分52秒

I am not very convinced it will respect summer tme (DST)?

2018年08月15日23分52秒

The JVM’s current default time zone can change at any moment during runtime. Any code in any thread of any app within the JVM can call TimeZone.setDefault. Your code is calling ZoneId.systemDefault twice, the first is implicit in LocalDate.now() and the second is explicit with atStartOfDay. In between those two moments at runtime, the current default zone could change. I suggest capturing the zone into a variable, and pass to both methods.

2018年08月16日23分52秒