Time formatting utility.
/*
TimeUtil.java / Freenet
Copyright (C) 2005-2006 The Free Network project
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
//package freenet.support;
import java.text.DecimalFormat;
/**
* Time formatting utility.
* Formats milliseconds into a week/day/hour/second/milliseconds string.
*/
public class TimeUtil {
/**
* It converts a given time interval into a
* week/day/hour/second.milliseconds string.
* @param timeInterval interval to convert
* @param maxTerms the terms number to display
* (e.g. 2 means "h" and "m" if the time could be expressed in hour,
* 3 means "h","m","s" in the same example).
* The maximum terms number available is 6
* @param withSecondFractions if true it displays seconds.milliseconds
* @return the formatted String
*/
public static String formatTime(long timeInterval, int maxTerms, boolean withSecondFractions) {
if (maxTerms > 6 )
throw new IllegalArgumentException();
StringBuilder sb = new StringBuilder(64);
long l = timeInterval;
int termCount = 0;
//
if(l < 0) {
sb.append('-');
l = l * -1;
}
if( !withSecondFractions && l < 1000 ) {
return "0";
}
if(termCount >= maxTerms) {
return sb.toString();
}
//
long weeks = (l / (7L*24*60*60*1000));
if (weeks > 0) {
sb.append(weeks).append('w');
termCount++;
l = l - (weeks * (7L*24*60*60*1000));
}
if(termCount >= maxTerms) {
return sb.toString();
}
//
long days = (l / (24L*60*60*1000));
if (days > 0) {
sb.append(days).append('d');
termCount++;
l = l - (days * (24L*60*60*1000));
}
if(termCount >= maxTerms) {
return sb.toString();
}
//
long hours = (l / (60L*60*1000));
if (hours > 0) {
sb.append(hours).append('h');
termCount++;
l = l - (hours * (60L*60*1000));
}
if(termCount >= maxTerms) {
return sb.toString();
}
//
long minutes = (l / (60L*1000));
if (minutes > 0) {
sb.append(minutes).append('m');
termCount++;
l = l - (minutes * (60L*1000));
}
if(termCount >= maxTerms) {
return sb.toString();
}
if(withSecondFractions && ((maxTerms - termCount) >= 2)) {
if (l > 0) {
double fractionalSeconds = l / (1000.0D);
DecimalFormat fix3 = new DecimalFormat("0.000");
sb.append(fix3.format(fractionalSeconds)).append('s');
termCount++;
//l = l - ((long)fractionalSeconds * (long)1000);
}
} else {
long seconds = (l / 1000L);
if (seconds > 0) {
sb.append(seconds).append('s');
termCount++;
//l = l - ((long)seconds * (long)1000);
}
}
//
return sb.toString();
}
public static String formatTime(long timeInterval) {
return formatTime(timeInterval, 2, false);
}
public static String formatTime(long timeInterval, int maxTerms) {
return formatTime(timeInterval, maxTerms, false);
}
}
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package freenet.support;
import java.util.Locale;
import junit.framework.TestCase;
/**
* Test case for {@link freenet.support.TimeUtil} class.
*
* @author Alberto Bacchelli <sback@freenetproject.org>
*/
public class TimeUtilTest extends TestCase {
//1w+1d+1h+1m+1s+1ms
private long oneForTermLong = 694861001;
@Override
protected void setUp() throws Exception {
Locale.setDefault(Locale.US);
}
/**
* Tests formatTime(long,int,boolean) method
* trying the biggest long value
*/
public void testFormatTime_LongIntBoolean_MaxValue() {
String expectedForMaxLongValue = "15250284452w3d7h12m55.807s";
assertEquals(TimeUtil.formatTime(Long.MAX_VALUE,6,true),
expectedForMaxLongValue);
}
/**
* Tests formatTime(long,int) method
* trying the biggest long value
*/
public void testFormatTime_LongInt() {
String expectedForMaxLongValue = "15250284452w3d7h12m55s";
assertEquals(TimeUtil.formatTime(Long.MAX_VALUE,6),
expectedForMaxLongValue);
}
/**
* Tests formatTime(long) method
* trying the biggest long value
*/
public void testFormatTime_Long() {
//it uses two terms by default
String expectedForMaxLongValue = "15250284452w3d";
assertEquals(TimeUtil.formatTime(Long.MAX_VALUE),
expectedForMaxLongValue);
}
/**
* Tests formatTime(long) method
* using known values.
* They could be checked using Google Calculator
* http://www.google.com/intl/en/help/features.html#calculator
*/
public void testFormatTime_KnownValues() {
Long methodLong;
String[][] valAndExpected = {
//one week
{"604800000","1w"},
//one day
{"86400000","1d"},
//one hour
{"3600000","1h"},
//one minute
{"60000","1m"},
//one second
{"1000","1s"}
};
for(int i = 0; i < valAndExpected.length; i++) {
methodLong = Long.valueOf(valAndExpected[i][0]);
assertEquals(TimeUtil.formatTime(methodLong.longValue()),
valAndExpected[i][1]); }
}
/**
* Tests formatTime(long,int) method
* using a long value that generate every possible
* term kind. It tests if the maxTerms arguments
* works correctly
*/
public void testFormatTime_LongIntBoolean_maxTerms() {
String[] valAndExpected = {
//0 terms
"",
//1 term
"1w",
//2 terms
"1w1d",
//3 terms
"1w1d1h",
//4 terms
"1w1d1h1m",
//5 terms
"1w1d1h1m1s",
//6 terms
"1w1d1h1m1.001s"
};
for(int i = 0; i < valAndExpected.length; i++)
assertEquals(TimeUtil.formatTime(oneForTermLong,i,true),
valAndExpected[i]);
}
/**
* Tests formatTime(long,int) method
* using one millisecond time interval.
* It tests if the withSecondFractions argument
* works correctly
*/
public void testFormatTime_LongIntBoolean_milliseconds() {
long methodValue = 1; //1ms
assertEquals(TimeUtil.formatTime(methodValue,6,false),"0");
assertEquals(TimeUtil.formatTime(methodValue,6,true),"0.001s");
}
/**
* Tests formatTime(long,int) method
* using a long value that generate every possible
* term kind. It tests if the maxTerms arguments
* works correctly
*/
public void testFormatTime_LongIntBoolean_tooManyTerms() {
try {
TimeUtil.formatTime(oneForTermLong,7);
fail("Expected IllegalArgumentException not thrown"); }
catch (IllegalArgumentException anException) {
assertNotNull(anException); }
}
}
Related examples in the same category
1. | Date Era change | | |
2. | Date Format | | |
3. | The Time and Date Format Suffixes | | |
4. | Display standard 12-hour time format | | |
5. | Display complete time and date information | | |
6. | Display just hour and minute | | |
7. | Display month by name and number | | |
8. | DateFormat.getDateInstance(DateFormat.SHORT) | | |
9. | Use relative indexes to simplify the creation of a custom time and date format. | | |
10. | Date Format with Locale | | |
11. | Date Format Symbols | | |
12. | Decimal Format with different Symbols | | |
13. | Date format: "dd.MM.yy", "yyyy.MM.dd G 'at' hh:mm:ss z","EEE, MMM d, ''yy", "h:mm a", "H:mm", "H:mm:ss:SSS", "K:mm a,z","yyyy.MMMMM.dd GGG hh:mm aaa" | | |
14. | SimpleDateFormat.getAvailableLocales | | |
15. | DateFormat.SHORT | | |
16. | This is same as MEDIUM: DateFormat.getDateInstance().format(new Date()) | | |
17. | This is same as MEDIUM: DateFormat.getDateInstance(DateFormat.DEFAULT).format(new Date()) | | |
18. | DateFormat.getTimeInstance(DateFormat.MEDIUM, Locale.CANADA).format(new Date()) | | |
19. | DateFormat.getTimeInstance(DateFormat.LONG, Locale.CANADA).format(new Date()) | | |
20. | DateFormat.getTimeInstance(DateFormat.FULL, Locale.CANADA).format(new Date()) | | |
21. | DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA).format(new Date()) | | |
22. | DateFormat.getDateInstance(DateFormat.LONG) | | |
23. | DateFormat.getTimeInstance(DateFormat.SHORT) | | |
24. | DateFormat.getTimeInstance(DateFormat.LONG) | | |
25. | Parse date string input with DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.CANADA) | | |
26. | Simple Date Format Demo | | |
27. | Format date in Medium format | | |
28. | Format date in Long format | | |
29. | Format date in Full format | | |
30. | Format date in Default format | | |
31. | Formatting day of week using SimpleDateFormat | | |
32. | Formatting day of week in EEEE format like Sunday, Monday etc. | | |
33. | Formatting day in d format like 1,2 etc | | |
34. | Formatting day in dd format like 01, 02 etc. | | |
35. | Format hour in h (1-12 in AM/PM) format like 1, 2..12. | | |
36. | Format hour in hh (01-12 in AM/PM) format like 01, 02..12. | | |
37. | Format hour in H (0-23) format like 0, 1...23. | | |
38. | Format hour in HH (00-23) format like 00, 01..23. | | |
39. | Format hour in k (1-24) format like 1, 2..24. | | |
40. | Format hour in kk (01-24) format like 01, 02..24. | | |
41. | Format hour in K (0-11 in AM/PM) format like 0, 1..11. | | |
42. | Format hour in KK (00-11) format like 00, 01,..11. | | |
43. | Formatting minute in m format like 1,2 etc. | | |
44. | Format minutes in mm format like 01, 02 etc. | | |
45. | Format month in M format like 1,2 etc | | |
46. | Format Month in MM format like 01, 02 etc. | | |
47. | Format Month in MMM format like Jan, Feb etc. | | |
48. | Format Month in MMMM format like January, February etc. | | |
49. | Format seconds in s format like 1,2 etc. | | |
50. | Format seconds in ss format like 01, 02 etc. | | |
51. | Format date in dd/mm/yyyy format | | |
52. | Format date in mm-dd-yyyy hh:mm:ss format | | |
53. | Format year in yy format like 07, 08 etc | | |
54. | Format year in yyyy format like 2007, 2008 etc. | | |
55. | new SimpleDateFormat("hh") | | |
56. | new SimpleDateFormat("H") // The hour (0-23) | | |
57. | new SimpleDateFormat("m"): The minutes | | |
58. | new SimpleDateFormat("mm") | | |
59. | SimpleDateFormat("MM"): number based month value | | |
60. | new SimpleDateFormat("s"): The seconds | | |
61. | new SimpleDateFormat("ss") | | |
62. | new SimpleDateFormat("a"): The am/pm marker | | |
63. | new SimpleDateFormat("z"): The time zone | | |
64. | new SimpleDateFormat("zzzz") | | |
65. | new SimpleDateFormat("Z") | | |
66. | new SimpleDateFormat("hh:mm:ss a") | | |
67. | new SimpleDateFormat("HH.mm.ss") | | |
68. | new SimpleDateFormat("HH:mm:ss Z") | | |
69. | SimpleDateFormat("MM/dd/yy") | | |
70. | SimpleDateFormat("dd-MMM-yy") | | |
71. | SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z") | | |
72. | SimpleDateFormat("yyyy") | | |
73. | The month: SimpleDateFormat("M") | | |
74. | Three letter-month value: SimpleDateFormat("MMM") | | |
75. | Full length of month name: SimpleDateFormat("MMMM") | | |
76. | The day number: SimpleDateFormat("d") | | |
77. | Two digits day number: SimpleDateFormat("dd") | | |
78. | The day in week: SimpleDateFormat("E") | | |
79. | Full day name: SimpleDateFormat("EEEE") | | |
80. | Add AM PM to time using SimpleDateFormat | | |
81. | Simply format a date as "YYYYMMDD" | | |
82. | Java SimpleDateFormat Class Example("MM/dd/yyyy") | | |
83. | The format used is EEE, dd MMM yyyy HH:mm:ss Z in US locale. | | |
84. | Date Formatting and Localization | | |
85. | Get a List of Short Month Names | | |
86. | Get a List of Weekday Names | | |
87. | Get a List of Short Weekday Names | | |
88. | Change date formatting symbols | | |
89. | An alternate way to get week days symbols | | |
90. | ISO8601 formatter for date-time without time zone.The format used is yyyy-MM-dd'T'HH:mm:ss. | | |
91. | ISO8601 formatter for date-time with time zone. The format used is yyyy-MM-dd'T'HH:mm:ssZZ. | | |
92. | Parsing custom formatted date string into Date object using SimpleDateFormat | | |
93. | Parse with a custom format | | |
94. | Parsing the Time Using a Custom Format | | |
95. | Parse with a default format | | |
96. | Parse a date and time | | |
97. | Parse string date value input with SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z") | | |
98. | Parse string date value input with SimpleDateFormat("dd-MMM-yy") | | |
99. | Parse string date value with default format: DateFormat.getDateInstance(DateFormat.DEFAULT) | | |
100. | Find the current date format | | |
101. | Time format viewer | | |
102. | Date format viewer | | |
103. | Returns a String in the format Xhrs, Ymins, Z sec, for the time difference between two times | | |
104. | format Duration | | |
105. | Get Date Suffix | | |
106. | Date Format Cache | | |
107. | ISO8601 Date Format | | |
108. | Explode a date in 8 digit format into the three components. | | |
109. | Date To Iso Date Time | | |
110. | Iso Date Time To Date | | |
111. | Gets formatted time | | |
112. | Format Time To 2 Digits | | |
113. | ISO 8601 BASIC date format | | |
114. | Format As MySQL Datetime | | |
115. | new SimpleDateFormat( "EEE MMM d HH:mm:ss z yyyy", Locale.UK ) | | |
116. | Date parser for the ISO 8601 format. | | |
117. | Parse W3C Date format | | |
118. | Pack/Unpacks date stored in kdb format | | |
119. | Provides preset formatting for Dates. All dates are returned as GMT | | |
120. | Parse RSS date format to Date object. | | |
121. | Date format for face book | | |
122. | FastDateFormat is a fast and thread-safe version of java.text.SimpleDateFormat. | | |
123. | Date format and parse Util | | |
124. | XSD Date Time | | |
125. | Return a String value of Now() in a specify format | | |
126. | Format data to string with specified style. | | |
127. | extends Formatter | | |