SimpleDateFormat的机器人没有格式化预期 [英] SimpleDateFormat android not formatting as expected
问题描述
我想使用的SimpleDateFormat格式化由3个整数psented日期重新$ P $。
它看起来是这样的:
I'm trying to use SimpleDateFormat for formatting a date represented by 3 ints. It looks like this:
...
SimpleDateFormat sdfHour = new SimpleDateFormat("HH");
SimpleDateFormat sdfMinute = new SimpleDateFormat("mm");
SimpleDateFormat sdfSecond = new SimpleDateFormat("ss");
Calendar c = Calendar.getInstance();
c.setTimeZone(TimeZone.getDefault());
int hours = c.get(Calendar.HOUR_OF_DAY);
int minutes = c.get(Calendar.MINUTE);
int seconds = c.get(Calendar.SECOND);
String string_hours = sdfHour.format(hours);
String string_minutes = sdfMinute.format(minutes);
String string_seconds = sdfSecond.format(seconds);
和的输出
Log.d("tag", "Time string is: " + string_hours + ":" + string_minutes + ":" + string_seconds);
总是
Time string is: 19:00:00
我在做什么错在这里?
What am I doing wrong here?
推荐答案
SimpleDateFormat.format需要一个日期,而不是一个int。您使用的方法,这是重载版本接受一个长期的,实际上是从的时代,不到一小时一分钟或第二期待毫秒为你做的。
SimpleDateFormat.format expects a Date, not an int. The method you're using, which is the overloaded version that accepts a long, is actually expecting milliseconds from the epoch, not an hour a minute or a second as you're doing.
使用它应该是正确的做法:
The right way of using it should be :
SimpleDateFormat sdfHour = new SimpleDateFormat("HH:mm:ss");
String timeString = sdfHour.format(new Date());
使用新的Date()在这个例子中,将给你当前时间。如果您需要格式化某个时间(比如一小时前,或从数据库等东西..)传递到格式正确的日期实例。
Using "new Date()" as in this example, will give you the current time. If you need to format some other time (like one hour ago, or something from a database etc..) pass to "format" the right Date instance.
如果您需要的分离,因为某些原因,那么你仍然可以使用,但是,这个另一种方式:
If you need the separated, for some reason, then you can still use it, but this other way :
SimpleDateFormat sdfHour = new SimpleDateFormat("HH");
SimpleDateFormat sdfMinute = new SimpleDateFormat("mm");
SimpleDateFormat sdfSecond = new SimpleDateFormat("ss");
Date now = new Date();
String string_hours = sdfHour.format(now);
String string_minutes = sdfMinute.format(now);
String string_seconds = sdfSecond.format(now);
这篇关于SimpleDateFormat的机器人没有格式化预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!