Skip to content

Commit f83798f

Browse files
Merge pull request eugenp#5512 from MrSamMillington/master
[BAEL-2256] Guide to simple date format unit test
2 parents 6e08650 + 06be85c commit f83798f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.baeldung;
2+
3+
import org.junit.Test;
4+
5+
import java.text.DateFormat;
6+
import java.text.SimpleDateFormat;
7+
import java.util.Date;
8+
import java.util.Locale;
9+
import java.util.TimeZone;
10+
import java.util.logging.Logger;
11+
12+
import static org.junit.Assert.assertEquals;
13+
import static org.junit.Assert.assertTrue;
14+
15+
16+
public class SimpleDateFormatUnitTest {
17+
18+
private static final Logger logger = Logger.getLogger(SimpleDateFormatUnitTest.class.getName());
19+
20+
@Test
21+
public void givenSpecificDate_whenFormatted_thenCheckFormatCorrect() throws Exception {
22+
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
23+
assertEquals("24-05-1977", formatter.format(new Date(233345223232L)));
24+
}
25+
26+
@Test
27+
public void givenSpecificDate_whenFormattedUsingDateFormat_thenCheckFormatCorrect() throws Exception {
28+
DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT);
29+
assertEquals("5/24/77", formatter.format(new Date(233345223232L)));
30+
}
31+
32+
@Test
33+
public void givenStringDate_whenParsed_thenCheckDateCorrect() throws Exception{
34+
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
35+
Date myDate = new Date(233276400000L);
36+
Date parsedDate = formatter.parse("24-05-1977");
37+
assertEquals(myDate.getTime(), parsedDate.getTime());
38+
}
39+
40+
@Test
41+
public void givenFranceLocale_whenFormatted_thenCheckFormatCorrect() throws Exception{
42+
SimpleDateFormat franceDateFormatter = new SimpleDateFormat("EEEEE dd-MMMMMMM-yyyy", Locale.FRANCE);
43+
Date myWednesday = new Date(1539341312904L);
44+
assertTrue(franceDateFormatter.format(myWednesday).startsWith("vendredi"));
45+
}
46+
47+
@Test
48+
public void given2TimeZones_whenFormatted_thenCheckTimeDifference() throws Exception {
49+
Date now = new Date();
50+
51+
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE dd-MMM-yy HH:mm:ssZ");
52+
53+
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
54+
logger.info(simpleDateFormat.format(now));
55+
//change the date format
56+
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
57+
logger.info(simpleDateFormat.format(now));
58+
}
59+
}

0 commit comments

Comments
 (0)