繁体   English   中英

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

[英]how to pass hour, minute and second in calendar object in 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。 某些时区的异常意味着这一天可能会在另一个时间点开始,例如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的偏移量。 但是,如果你坚持,你可以使用一个DateTimeFormatter在java.time预先定义不包括区/偏移: DateTimeFormatter.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类?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM