如何在Java中获得无时间的日期? [英] How do I get a Date without time in Java?

查看:79
本文介绍了如何在Java中获得无时间的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续从堆栈溢出问题 获得当前日期的Java程序没有时间戳

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

没有时间获取Date对象最有效的方法是什么?有没有其他方法比这两个?

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();

更新


  1. 我知道 Joda-Time ;我只是试图避免额外的图书馆这样一个简单(我认为)的任务。但是根据迄今为止的答案,Joda-Time似乎非常受欢迎,所以我可以考虑一下。

  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.

通过高效我想避免由方法1 使用的临时对象 String 创建,同时方法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.


推荐答案

p>你是否绝对使用 java.util.Date ?我会彻底 建议您使用 Joda时间 java.time 包从Java 8替代。特别是,虽然日期和日历总是代表一个特定的时刻,但是没有这样的概念就像只是一个日期,Joda Time 有一个类型代表这个( LocalDate )。如果您能够使用代表您实际想做什么的类型,您的代码将会更加清晰。

Do you absolutely have to use java.util.Date? I would thoroughly recommend that you use Joda Time or the java.time package from Java 8 instead. In particular, while Date and Calendar always represent a particular instant in time, with no such concept as "just a date", Joda Time does have a type representing this (LocalDate). Your code will be much clearer if you're able to use types which represent what you're actually trying to do.

使用Joda有许多其他原因时间或 java.time 而不是内置的 java.util 类型 - 它们通常是更好的API。如果您需要,您可以随时转换为/ code> java.util.Date 在您自己的代码的边界。用于数据库交互。

There are many, many other reasons to use Joda Time or java.time instead of the built-in java.util types - they're generally far better APIs. You can always convert to/from a java.util.Date at the boundaries of your own code if you need to, e.g. for database interaction.

这篇关于如何在Java中获得无时间的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆