如何在android java中的日历对象中传递小时,分钟和秒

我做了一个我需要进行日期转换的应用程序。 这是我的代码。

GregorianCalendar c = new GregorianCalendar(Locale.GERMANY); c.set(2011, 04, 29,0,0,0); String cdate = (String) DateFormat.format("yyyy-MM-dd HH:mm:ss", c.getTime()); Log.i(tag,cdate); 

现在当我在这里检查我的LOG是输出:

04-22 12:44:15.956:INFO / GridCellAdapter(30248):2011-04-29 HH:00:00

为什么小时字段没有设置。 我在制作日历对象时显式传递了0,仍然在LOG中显示HH。 可能是什么问题呢?

先谢谢你。

使用小写hh:

 String cdate = (String) DateFormat.format("yyyy-MM-dd hh:mm:ss", c.getTime()); 

设置c.set(Calendar.HOUR_OF_DAY,0) ,它应该工作。 你试过这样的吗?

 c.set(Calendar.YEAR, 2009); c.set(Calendar.MONTH,11); c.set(Calendar.DAY_OF_MONTH,4); c.set(Calendar.HOUR_OF_DAY,0); c.set(Calendar.MINUTE,0); c.set(Calendar.SECOND,0) 

TL;博士

 LocalDate.of( 2011 , 4 , 29 ) // Represent April 29, 2011. .atStartOfDay( ZoneId.of( "America/Montreal" ) ) // Determine the first moment of the day. Often 00:00:00 but not always. .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) // Generate a String representing the value of this date, using standard ISO 8601 format. .replace( "T" , " " ) // Replace the `T` in the middle of standard ISO 8601 format with a space for readability. 

使用java.time

现代的方法是使用java.time类。

如果您想要获得当天的第一时刻,请不要假设时间00:00:00。 某些时区的exception意味着这一天可能会在另一个时间点开始,例如01:00:00。

LocalDate类表示没有时间且没有时区的仅日期值。

时区对于确定日期至关重要。 对于任何给定的时刻,日期在全球范围内因地区而异。 例如, 法国巴黎午夜过后几分钟,在魁北克蒙特利尔的 “昨天”仍然是新的一天。

continent/region的格式指定适当的时区名称 ,例如America/MontrealAfrica/CasablancaPacific/Auckland 。 切勿使用3-4字母缩写,例如ESTIST因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。

 ZoneId z = ZoneId.of( "America/Montreal" ); LocalDate today = LocalDate.now( z ); 

您想在问题中指定具体日期。

 LocalDate localDate = LocalDate.of( 2011 , 4 , 29 ) ; 

再次应用时区以确定当天的第一时刻。

 ZonedDateTime zdt = localDate.atStartOfDay( z ); // Determine the first moment of the day on this date for this zone. 

我建议始终在日期时间字符串中包含时区指示符或与UTC的偏移量。 但是如果你坚持,你可以使用在java.time中预定义的不包含zone / offset的DateTimeFormatter.ISO_LOCAL_DATE_TIMEDateTimeFormatter.ISO_LOCAL_DATE_TIME 。 只需从中间移除T

 String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) .replace( "T" , " " ) ; 

关于java.time

java.time框架内置于Java 8及更高版本中。 这些类取代了麻烦的旧遗留日期时间类,如java.util.DateCalendarSimpleDateFormat

现在处于维护模式的Joda-Time项目建议迁移到java.time类。

要了解更多信息,请参阅Oracle教程 。 并搜索Stack Overflow以获取许多示例和解释。 规范是JSR 310 。

从哪里获取java.time类?

  • Java SE 8Java SE 9及更高版本
    • 内置。
    • 带有捆绑实现的标准Java API的一部分。
    • Java 9增加了一些小function和修复。
  • Java SE 6Java SE 7
    • 许多java.timefunction都被反向移植到ThreeTen-Backport中的 Java 6和7。
  • Android的
    • ThreeTenABP项目特别适用于Android的ThreeTen-Backport (如上所述)。
    • 请参见如何使用ThreeTenABP ….