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

Java program to get the current date without timestamp

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

1
Date d = new Date();

给我日期和时间戳。

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

打印时

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

共d张,打印May 11 2010 - 00:00:00


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

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

1
2
3
4
5
6
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);

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

如Java.UTI.Calase.Currar(int字段)的JavaDoc说明:

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中,包EDCOX1 7中有一个新的日期和时间API,它比旧EDCOX1 1和EDCOX1 9个类更强大和有用。使用新的日期和时间类而不是旧的。


你可以一直使用ApacheCommons的DateUtils类。它有一个静态方法isSameDay(),它"检查两个日期对象是否在同一天,忽略时间"。

1
static boolean isSameDay(Date date1, Date date2)


使用dateformat解决此问题:

1
2
3
4
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateFormat2 = new SimpleDateFormat("MM-dd-yyyy");
print(dateFormat.format(new Date()); // will print like 2014-02-20
print(dateFormat2.format(new Date()); // will print like 02-20-2014


我做了如下的工作:(没有时间戳的当前日期)

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


你可以用

1
2
3
4
5
6
7
8
// 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"

查看FormatterAPI文档。


你可以在这个日期前得到:

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


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


也可以使用apache commons lib DateUtils.truncate()

1
2
Date now = new Date();
Date truncated = DateUtils.truncate(now, Calendar.DAY_OF_MONTH);

时间将设置为00:00:00,以便您可以使用此日期或打印格式:

1
2
3
4
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

System.out.println(dateFormat.format(now);        // 2010-05-11 11:32:47
System.out.println(dateFormat.format(truncated);  // 2010-05-11 00:00:00


杰斯帕接受的回答是正确的,但现在已经过时了。java.util.date和.calendar类是出了名的麻烦事。避开他们。

java.time时间

相反,使用Java.TimeFrand,内置到Java 8和以后,返回到Java 6和7,并进一步适应Android。

如果您真的不关心时间和时区,请在java.time框架()中使用LocalDate

1
LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );

请注意,如果您有任何机会需要处理其他时区或UTC,这是错误的做法。Na?VE程序员往往认为他们不需要时区,而实际上他们需要时区。

调用toString生成标准ISO 8601格式的字符串。

1
String output = localDate.toString();

2014-05-06

对于其他格式,搜索DateTimeFormatter类的堆栈溢出。

乔达时间

虽然现在被javatime取代了,但可以在JoDA时间库中使用类似的EDCOX1 12级类(Java.Time的灵感)。

1
LocalDate localDate = new LocalDate( 2014, 5, 6 );


1
2
3
4
5
6
7
8
9
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();
        }
    }

如果您真的想用日期代替日历进行比较,这是您可以使用的最短代码:

1
2
3
4
Calendar c = Calendar.getInstance();
Date d = new GregorianCalendar(c.get(Calendar.YEAR),
                               c.get(Calendar.MONTH),
                               c.get(Calendar.DAY_OF_MONTH)).getTime();

这样可以确保小时/分钟/秒/毫秒值为空。


这是一个完整的例子,但你必须把刺抛回历史。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

//TODO OutPut should LIKE in this format MM dd yyyy HH:mm:ss.SSSSSS
public class TestDateExample {

    public static void main(String args[]) throws ParseException {
        SimpleDateFormat changeFormat = new SimpleDateFormat("MM dd yyyy HH:mm:ss.SSSSSS");
         Date thisDate = new Date();//changeFormat.parse("10 07 2012");
         System.out.println("Current Date :" + thisDate);
         changeFormat.format(thisDate);
        System.out.println("----------------------------");
        System.out.println("After applying formating :");
        String strDateOutput = changeFormat.format(thisDate);
        System.out.println(strDateOutput);

    }

}

Eaxmple


我在寻找同样的解决方案,下面的方法对我很有效。

1
2
3
4
5
6
7
8
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.clear(Calendar.HOUR);
    calendar.clear(Calendar.MINUTE);
    calendar.clear(Calendar.SECOND);
    calendar.clear(Calendar.MILLISECOND);

    Date today = calendar.getTime();

请注意,我正在使用calendar.set(calendar.hour_of_day,0)for hour_day,而不是使用clear方法,因为calendar.clear方法的javadocs中建议如下

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.

通过上面发布的解决方案,我得到的输出为

1
Wed Sep 11 00:00:00 EDT 2013

在12点后执行时,使用清除法将12点后的小时重置为12,在12点前执行时重置为00。


这是一种不雅的快速实现方法,不需要额外的依赖。您可以只使用java.sql.date,它扩展了java.util.date,但是为了进行比较,您必须比较字符串。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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);

输出:

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


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

1
2
3
4
5
6
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();

或者相反。在日历中放入要比较的日期,然后比较日历日期

1
2
3
4
5
6
7
8
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!
}


这是我的"只获取日期"代码:

1
2
3
4
Calendar c=Calendar.getInstance();
DateFormat dm = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date = new java.util.Date();
System.out.println("current date is :   " + dm.format(date));


我做了如下工作:

1
2
3
4
5
6
7
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

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