-
-
Save liquiddandruff/ca4eb98fdd063b6c250b to your computer and use it in GitHub Desktop.
Most common formats for String.format(..)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import java.util.Date; | |
import static org.junit.Assert.assertEquals; | |
public class StringFormatTest { | |
@Test public void basicInteger() { | |
assertEquals("123456", String.format("%d", 123456)); | |
} | |
@Test public void leftPaddingIntegerWithZeroes() { | |
assertEquals("007", String.format("%03d", 7)); | |
} | |
@Test public void integerWithLeadingSpace() { | |
assertEquals(" 11", String.format("% 4d", 11)); | |
} | |
@Test public void floatWithTwoDecimals() { | |
assertEquals("1123.35", String.format("%.2f", 1123.345566)); | |
} | |
@Test public void time() { | |
assertEquals("09:26:42", String.format("%tT", 1312180002230L)); | |
} | |
@Test public void date() { | |
assertEquals("2011-08-01", String.format("%tF", new Date(1312180002230L))); | |
} | |
@Test public void dateAndTime() { | |
assertEquals("09:26:42.231 2011.08.01", String.format("%1$tH:%1$tM:%1$tS.%1$tL %1$tY.%1$tm.%1$td", 1312180002231L)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Couldn't find that L flag for milliseconds anywhere! (line 32) Saving here for future needs