所以我有一个字符串是" 2014-06-30 15:27"如果是今天的日期,它应该只返回" 15:27"否则" 30/06 / 2014"。我已经尝试过simpleDateFormat.parse,但它并没有很好地工作。
holder.data.setText(mensagem.getDate());
答案 0 :(得分:3)
final String stringDate = "2014-07-17 23:59";
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = inputFormat.parse(stringDate);
Calendar calendarDate = Calendar.getInstance();
calendarDate.setTime(date);
Calendar midnight = Calendar.getInstance();
midnight.set(Calendar.HOUR_OF_DAY, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MILLISECOND, 0);
if (calendarDate.compareTo(midnight) >= 0)
{
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
System.out.println(timeFormat.format(date));
}
else
{
SimpleDateFormat dateTimeForm = new SimpleDateFormat("dd/MM/yyyy HH:mm");
System.out.println(dateTimeForm.format(date));
}
答案 1 :(得分:0)
LocalDateTime
首先将字符串解析为LocalDateTime
。用T
替换中间的SPACE以符合标准ISO 8601格式。默认情况下,java.time类支持ISO 8601格式。
LocalDateTime ldt = LocalDateTime.parse ( "2014-06-30 15:27".replace ( " " , "T" ) );
ldt.toString():2014-06-30T15:27
这样的价值没有实际意义。输入字符串缺少关于UTC或时区偏移的任何线索。所以我们不知道这是新西兰奥克兰的下午3点还是加拿大魁北克省的下午3点,两个非常不同的时刻。您应该指定业务情况指示的偏移量或时区。搜索Stack Overflow以了解如何执行此操作,重点关注类OffsetDateTime
和ZonedDateTime
。我现在暂时跳过这个关键问题。
LocalDate
提取仅限日期的值。 LocalDate
类表示没有时间且没有时区的仅限日期的值。
LocalDate ld = ldt.toLocalDate();
时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因地区而异。例如,在Paris France午夜后的几分钟是新的一天,而Montréal Québec中仍然是“昨天”。
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
您可以通过调用compareTo
,equals
,isEqual
,isBefore
,isAfter
等方法来比较LocalDate
个对象。
if( today.isEqual( ld ) ) {
return ldt.toLocalTime();
} else {
return ld;
}
java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.Date
,Calendar
和& SimpleDateFormat
现在位于Joda-Time的maintenance mode项目建议迁移到java.time类。
要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310。
您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*
类。
从哪里获取java.time类?
ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如Interval
,YearWeek
,YearQuarter
和more。
答案 2 :(得分:0)
只需使用Date类...
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date exitdate = df.parse("2019-01-17");
Date currdate = new Date();
long diff = currdate.getTime() - exitdate.getTime();
long days = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
if(days==0)
{
System.out.println("IS TRUE"+currdate.toString());
return true;
}