2009-02-12 80 views
2

有没有办法格式化一个日期以使mmm:ss代替hh:mm:ss?基本上,7:15:28应该显示为435:28。自定义日期格式mmm:ss

SimpleDateFormat类不支持这种格式是否有一个或我将不得不自己实现一个变体?

回答

4

你必须自己实现它,但是你应该记住,实现Formatter并不是一项简单的任务,因为它有很多l10n的考虑因素。

+0

这是据你所知,或者你确定没有可以处理这种格式的软件包吗? – 2009-02-12 17:22:48

1

您可以使用Joda Time构建自定义格式器。随着DateTimeFormatterBuilder类,你至少可以表明,每天的分钟:

import org.joda.time.format.DateTimeFormatter; 
import org.joda.time.format.DateTimeFormatterBuilder; 

DateTimeFormatter customFormat = new DateTimeFormatterBuilder() 
     .appendMinuteOfDay(1) 
     .appendLiteral(':') 
     .appendSecondOfMinute(2) 
     .toFormatter(); 
System.out.println(customFormat.print(System.currentTimeMillis())); 
2

如果你想要做的是格式的日期到您指定的格式(与日期包含的任何其他部分),你只需这很简单:

public String format(Date date) {  
     Calendar cal = new GregorianCalendar(); 
     cal.setTime(date); 
     return cal.get(Calendar.HOUR) * 60 + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND);  
    }