Java程序获取没有时间戳的当前日期 [英] Java program to get the current date without timestamp

查看:383
本文介绍了Java程序获取没有时间戳的当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个Java程序来获取当前日期而没有时间戳

I need a Java program to get the current date without a timestamp:

Date d = new Date();

给我日期和时间戳。

但我只需要日期,没有时间戳。我使用此日期与另一个没有时间戳的日期对象进行比较。

But I need only the date, without a timestamp. I use this date to compare with another date object that does not have a timestamp.

打印时

System.out.println("Current Date : " + d)

它应该打印 2010年5月11日 - 00:00:00

推荐答案

java.util.Date object 一种时间戳 - 它包含自1970年1月1日00以来的毫秒数:00:00 UTC所以你不能使用标准的 Date 对象来包含一天/月/年,没有时间。

A java.util.Date object is a kind of timestamp - it contains a number of milliseconds since January 1, 1970, 00:00:00 UTC. So you can't use a standard Date object to contain just a day / month / year, without a time.

据我所知,通过仅在标准Java API中考虑日期(而不是时间)来比较日期并不是一种非常简单的方法。您可以使用类日历并清除小时,分钟,秒和毫秒:

As far as I know, there's no really easy way to compare dates by only taking the date (and not the time) into account in the standard Java API. You can use class Calendar and clear the hour, minutes, seconds and milliseconds:

Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.AM_PM);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

对另一个日历对象做同样的事情包含你要比较它的日期,并使用 after()之前()方法来做比较。

Do the same with another Calendar object that contains the date that you want to compare it to, and use the after() or before() methods to do the comparison.

正如 java.util.Calendar.clear(int field)的Javadoc所解释的那样:

As explained into the Javadoc of java.util.Calendar.clear(int field):


独立处理 HOUR_OF_DAY HOUR AM_PM 字段及其分辨率适用于一天中的时间规则。清除其中一个字段不会重置此日历的小时值。使用set(Calendar.HOUR_OF_DAY,0)重置小时值。

The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.

编辑 - 上面的答案是从2010年;在Java 8中,包 java.time 中有一个新的日期和时间API,它比旧的 java.util更强大,更有用。 .Date java.util.Calendar 类。使用新的日期和时间类而不是旧的。

edit - The answer above is from 2010; in Java 8, there is a new date and time API in the package java.time which is much more powerful and useful than the old java.util.Date and java.util.Calendar classes. Use the new date and time classes instead of the old ones.

这篇关于Java程序获取没有时间戳的当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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