2014-09-22 51 views
1

我试图使用SimpleDateFormat格式化由3个整数表示的日期。 它看起来像这样:SimpleDateFormat android未按预期格式化

... 
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 

我在做什么错在这里?

+1

您期望的是什么? – 2014-09-22 10:38:26

回答

4

SimpleDateFormat.format需要日期,而不是int。您正在使用的方法,即接受长时间的重载版本,实际上期望从时代开始毫秒,而不是像您一样每分钟或一秒钟。

使用它应该是正确的做法:

SimpleDateFormat sdfHour = new SimpleDateFormat("HH:mm:ss"); 
String timeString = sdfHour.format(new Date()); 

使用“新的Date()”在这个例子中,会给你的当前时间。如果你需要格式化一些其他的时间(比如一小时前,或者某个数据库中的东西等),通过格式化正确的Date实例。

如果您需要分离,出于某种原因,那么你仍然可以使用,但是,这个另一种方式:

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); 
1

不能使用SimpleDateFormat这样的:

SimpleDateFormat sdfHour = new SimpleDateFormat("HH"); 
SimpleDateFormat sdfMinute = new SimpleDateFormat("mm"); 
SimpleDateFormat sdfSecond = new SimpleDateFormat("ss"); 

使用这样的:

long timeInMillis = System.currentTimeMillis(); 
Calendar cal1 = Calendar.getInstance(); 
cal1.setTimeInMillis(timeInMillis); 
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss"); 
String dateformatted = dateFormat.format(cal1.getTime()); 

参考this

1

尝试是这样的:

Calendar cal = Calendar.getInstance(); 
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
String CurrentTime = sdf.format(cal.getTime()); 
+1

希望这可以帮助你! – 2014-09-22 10:40:30

+0

简单和工作。谢谢! – Marcus 2014-09-22 10:47:14

+0

如果它适合你,那么请接受我的回答 – 2014-09-22 10:48:03

1

要调用错误format方法。你应该提供一个Date参数中合适的一个,而是你正使用该one,从Format类继承:

public final String format(Object obj) 

为什么它的工作?由于Java中的自动装箱过程。您提供了一个int,它会自动装箱到Integer,这是Object的继任者