[英]Java program to get the current date without timestamp
我需要一个 Java 程序来获取没有时间戳的当前日期:
Date d = new Date();
给我日期和时间戳。
但我只需要日期,没有时间戳。 我使用这个日期与另一个没有时间戳的日期对象进行比较。
印刷时
System.out.println("Current Date : " + d)
d 它应该打印May 11 2010 - 00:00:00
。
java.util.Date
对象是一种时间戳 - 它包含自 1970 年 1 月 1 日 00:00:00 UTC 以来的毫秒数。 因此,您不能使用标准Date
对象只包含一天/月/年,而没有时间。
据我所知,在标准 Java API 中只考虑日期(而不是时间)并没有真正简单的方法来比较日期。 您可以使用Calendar
类并清除小时、分钟、秒和毫秒:
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.util.Calendar.clear(int field)的 Javadoc 中所解释的:
HOUR_OF_DAY 、 HOUR和AM_PM字段是独立处理的,并且应用了一天中的时间的解析规则。 清除其中一个字段不会重置此日历的一天中的小时值。 使用 set(Calendar.HOUR_OF_DAY, 0) 重置小时值。
编辑- 以上答案来自 2010 年; 在 Java 8 中,包java.time
有一个新的日期和时间 API,它比旧的java.util.Date
和java.util.Calendar
类更强大和有用。 使用新的日期和时间类而不是旧的。
你总是可以使用apache commons的DateUtils
类。 它有静态方法isSameDay()
,它“检查两个日期对象是否在同一天忽略时间”。
static boolean isSameDay(Date date1, Date date2)
使用DateFormat来解决这个问题:
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
我做了以下工作并且它有效:(当前日期没有时间戳)
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date today = dateFormat.parse(dateFormat.format(new Date()));
您可以在此日期之前获得:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
print(dateFormat.format(new Date());
你可以用
// 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"
DateFormat dateFormat = new SimpleDateFormat("MMMM dd yyyy");
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
Jesper 接受的答案是正确的,但现在已经过时了。 java.util.Date 和 .Calendar 类是出了名的麻烦。 避开它们。
而是使用java.time框架,内置于 Java 8 及更高版本中,向后移植到 Java 6 和 7并进一步适应 Android 。
如果你真的不关心时间和时区,使用 java.time 框架中的LocalDate
()。
LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );
时区对于确定日期至关重要。 对于任何给定时刻,日期因地区而异。 例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天”。
如果未指定时区,JVM 会隐式应用其当前默认时区。 该默认值可能会在运行时随时更改(!),因此您的结果可能会有所不同。 最好将您想要/预期的时区明确指定为参数。 如果您想使用 JVM 的当前默认时区,请通过调用ZoneId.systemDefault()
明确您的意图。 如果关键,请与您的用户确认该区域。
以Continent/Region
格式指定正确的时区名称,例如America/Montreal
、 Africa/Casablanca
或Pacific/Auckland
。 永远不要使用EST
或IST
等 2-4 个字母的缩写,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。 如果省略,代码读起来会变得模棱两可,因为我们不确定您是否打算使用默认值,或者您是否像许多程序员一样没有意识到这个问题。
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;
如果您关心特定时刻、时间线上的特定点,请不要使用LocalDate
。 如果您关心通过某个地区的人们使用的挂钟时间看到的日期,请不要使用LocalDate
。
要知道,如果你有需要处理其他时区或UTC的任何机会,这是错误的路要走。 天真的程序员往往认为他们不需要时区,但实际上他们确实需要时区。
调用toString
以生成标准ISO 8601格式的字符串。
String output = localDate.toString();
2014-05-06
对于其他格式,在 Stack Overflow 中搜索DateTimeFormatter
类。
虽然现在被 java.time 取代,但您可以使用Joda-Time库中类似的LocalDate
类(java.time 的灵感)。
LocalDate localDate = new LocalDate( 2014, 5, 6 );
您也可以使用 apache commons lib DateUtils.truncate()
:
Date now = new Date();
Date truncated = DateUtils.truncate(now, Calendar.DAY_OF_MONTH);
时间将设置为00:00:00
因此您可以使用此日期或格式化打印:
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
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();
}
}
我做了以下工作,它起作用了:
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
对要比较的其他实例执行此操作。 这个逻辑对我有用; 我必须比较日期是否相等,但是您可以进行不同的比较(之前、之后、等于等)
如果您真的想使用 Date 代替 Calendar 进行比较,这是您可以使用的最短代码:
Calendar c = Calendar.getInstance();
Date d = new GregorianCalendar(c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).getTime();
这样您就可以确保小时/分钟/秒/毫秒值是空白的。
我正在寻找相同的解决方案,以下对我有用。
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) 作为 HOUR_OF_DAY 而不是使用 clear 方法,因为在 Calendar.clear 方法的 javadocs 中建议如下
HOUR_OF_DAY、HOUR 和 AM_PM 字段是独立处理的,并且应用了一天中的时间的解析规则。 清除其中一个字段不会重置此日历的一天中的小时值。 使用 set(Calendar.HOUR_OF_DAY, 0) 重置小时值。
使用上面发布的解决方案,我得到的输出为
Wed Sep 11 00:00:00 EDT 2013
对 HOUR_OF_DAY 使用 clear 方法在 12PM 之后执行时将小时重置为 12 或在 12PM 之前执行时将小时重置为 00。
我认为这会奏效。 使用日历操作时间字段(将它们重置为零),然后从日历中获取日期。
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();
或者做相反的事情。 将要比较的日期放入日历并比较日历日期
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!
}
这是一种在没有额外依赖的情况下快速完成的不优雅方式。
您可以只使用 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);
输出:
当前日期1 : 2010-05-10
当前日期2 : 2010-05-10
日期比较错误
字符串比较为真
这是我仅获取日期的代码:
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));
这是它的完整示例。但是您必须将 Sting 转换回 Date。
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.