Java程序获取没有时间戳的当前日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2806360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:02:56  来源:igfitidea点击:

Java program to get the current date without timestamp

java

提问by minil

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

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

Date d = new Date();

gives me date and timestamp.

给我日期和时间戳。

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.

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

On printing

印刷时

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

of d it should print May 11 2010 - 00:00:00.

d 它应该打印May 11 2010 - 00:00:00

采纳答案by Jesper

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

一个java.util.Date对象一种时间戳的-它包含自00:00:00 1970年1月1日,UTC毫秒数。因此,您不能使用标准Date对象只包含一天/月/年,而没有时间。

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 Calendarand clear the hour, minutes, seconds and milliseconds:

据我所知,在标准 Java API 中只考虑日期(而不是时间)并没有真正简单的方法来比较日期。您可以使用 classCalendar并清除小时、分钟、秒和毫秒:

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

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

对另一个Calendar包含要与之进行比较的日期的对象执行相同操作,并使用after()before()方法进行比较。

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

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

The HOUR_OF_DAY, HOURand AM_PMfields 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.

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

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

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

回答by aioobe

You could use

你可以用

// Format a string containing a date.
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;

Calendar c = GregorianCalendar.getInstance();
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"

Have a look at the FormatterAPI documentation.

查看FormatterAPI 文档

回答by Il-Bhima

  DateFormat dateFormat = new SimpleDateFormat("MMMM dd yyyy");
  java.util.Date date = new java.util.Date();
  System.out.println("Current Date : " + dateFormat.format(date));

回答by Jonathan M Davis

You could always use apache commons' DateUtilsclass. It has the static method isSameDay()which "Checks if two date objects are on the same day ignoring time."

你总是可以使用Apache的百科全书DateUtils类。它具有isSameDay()“检查两个日期对象是否在同一天忽略时间”的静态方法。

static boolean isSameDay(Date date1, Date date2) 

回答by staticman

I think this will work. Use Calendar to manipulate time fields (reset them to zero), then get the Date from the Calendar.

我认为这会奏效。使用日历操作时间字段(将它们重置为零),然后从日历中获取日期。

Calendar c = GregorianCalendar.getInstance();
c.clear( Calendar.HOUR_OF_DAY );
c.clear( Calendar.MINUTE );
c.clear( Calendar.SECOND );
c.clear( Calendar.MILLISECOND );
Date today = c.getTime();

Or do the opposite. Put the date you want to compare to in a calendar and compare calendar dates

或者做相反的事情。将要比较的日期放入日历并比较日历日期

Date compareToDate;  // assume this is set before going in.
Calendar today = GregorianCalendar.getInstance();
Calendar compareTo = GregorianCalendar.getInstance();
compareTo.setTime( compareToDate );
if( today.get( Calendar.YEAR ) == compareTo.get( Calendar.YEAR ) &&
    today.get( Calendar.DAY_OF_YEAR  ) == compareTo.get( Calendar.DAY_OF_YEAR  ) ) {
  // They are the same day!
}

回答by crowne

Here's an inelegant way of doing it quick without additional dependencies.
You could just use java.sql.Date, which extends java.util.Date although for comparisons you will have to compare the Strings.

这是一种在没有额外依赖的情况下快速完成的不优雅方式。
您可以只使用 java.sql.Date,它扩展了 java.util.Date,但为了进行比较,您必须比较字符串。

java.sql.Date dt1 = new java.sql.Date(System.currentTimeMillis());
String dt1Text = dt1.toString();
System.out.println("Current Date1 : " + dt1Text);

Thread.sleep(2000);

java.sql.Date dt2 = new java.sql.Date(System.currentTimeMillis());
String dt2Text = dt2.toString();
System.out.println("Current Date2 : " + dt2Text);

boolean dateResult = dt1.equals(dt2);
System.out.println("Date comparison is " + dateResult);
boolean stringResult = dt1Text.equals(dt2Text);
System.out.println("String comparison is " + stringResult);

Output:

输出:

Current Date1 : 2010-05-10
Current Date2 : 2010-05-10
Date comparison is false
String comparison is true

当前日期 1 : 2010-05-10
当前
日期2 : 2010-05-10日期比较为假
字符串比较为真

回答by valsaraj

private static final DateFormat df1 = new SimpleDateFormat("yyyyMMdd"); 
    private static Date NOW = new Date();
    static {
        try {
            NOW = df1.parse(df1.format(new Date()));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

回答by Coral

I did as follows and it worked:

我做了以下工作,它起作用了:

calendar1.set(Calendar.HOUR_OF_DAY, 0);
calendar1.set(Calendar.AM_PM, 0);
calendar1.set(Calendar.HOUR, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
Date date1 = calendar1.getTime();       // Convert it to date

Do this for other instances to which you want to compare. This logic worked for me; I had to compare the dates whether they are equal or not, but you can do different comparisons (before, after, equals, etc.)

对要比较的其他实例执行此操作。这个逻辑对我有用;我必须比较日期是否相等,但是您可以进行不同的比较(之前、之后、等于等)

回答by Kyaw

I did as follows and it worked: (Current date without timestamp)

我做了以下工作并且它有效:(当前日期没有时间戳)

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date today = dateFormat.parse(dateFormat.format(new Date()));

回答by Amit

You can get by this date:

您可以在此日期之前获得:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
print(dateFormat.format(new Date());