2011-04-22 69 views
1

我已经提出了一个需要执行日期转换的应用程序。 这是我的代码。如何在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是输出:

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

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

谢谢你提前。

回答

1

设置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) 
+0

nopes,不工作。试过了。 – user590849 2011-04-22 07:27:30

3

使用小写HH:

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

这样一个简单的解决方案。它的工作....当我检查在Android网站[这里](http://developer.android.com/reference/java/text/SimpleDateFormat.html)他们使用HH .....不知道什么正在发生。 – user590849 2011-04-22 08:09:59

+0

请接受答案,如果有帮助。 – 2011-04-22 08:33:24

+2

hh表示12小时制,HH表示24小时制。我需要24小时制的结果。 – user590849 2011-04-22 09:25:29

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类代表没有时间和不带时区的仅有日期的值。

时区对确定日期至关重要。对于任何特定的时刻,日期因地区而异。例如,Paris France午夜后几分钟是新的一天,而在Montréal Québec仍然是“昨天”。

continent/region的格式指定一个proper time zone name,如America/MontrealAfrica/Casablanca,或Pacific/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中预定义的DateTimeFormatter,它不包含区域/偏移量:DateTimeFormatter.ISO_LOCAL_DATE_TIME。仅从中间删除T

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

关于java.time

java.time框架是建立在Java 8和更高版本。这些类取代了日期时间类legacy,如java.util.Date,Calendar,& SimpleDateFormat

Joda-Time项目现在位于maintenance mode,建议迁移到java.time类。请参阅Oracle Tutorial。并搜索堆栈溢出了很多例子和解释。规格是JSR 310

从何处获取java.time类?

相关问题