Added Create Date class & Unit Tests for all the cases (#8499)

This commit is contained in:
Vijay Palaniappan S 2020-01-09 23:28:12 +05:30 committed by maibin
parent 1d0db565e0
commit 08a1af18fb
2 changed files with 101 additions and 0 deletions

View File

@ -0,0 +1,45 @@
package com.baeldung.datebasics;
import java.time.Clock;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class CreateDate {
public LocalDate getTodaysDate() {
return LocalDate.now();
}
public LocalDate getTodaysDateFromClock() {
return LocalDate.now(Clock.systemDefaultZone());
}
public LocalDate getTodaysDateFromZone(String zone) {
return LocalDate.now(ZoneId.of(zone));
}
public LocalDate getCustomDateOne(int year, int month, int dayOfMonth) {
return LocalDate.of(year, month, dayOfMonth);
}
public LocalDate getCustomDateTwo(int year, Month month, int dayOfMonth) {
return LocalDate.of(year, month, dayOfMonth);
}
public LocalDate getDateFromEpochDay(long epochDay) {
return LocalDate.ofEpochDay(epochDay);
}
public LocalDate getDateFromYearAndDayOfYear(int year, int dayOfYear) {
return LocalDate.ofYearDay(year, dayOfYear);
}
public LocalDate getDateFromString(String date) {
return LocalDate.parse(date);
}
public LocalDate getDateFromStringAndFormatter(String date, String pattern) {
return LocalDate.parse(date, DateTimeFormatter.ofPattern(pattern));
}
}

View File

@ -0,0 +1,56 @@
package com.baeldung.datebasics;
import static org.junit.Assert.assertEquals;
import java.time.Month;
import org.junit.Test;
public class CreateDateUnitTest {
private CreateDate date = new CreateDate();
@Test
public void whenUsingNowMethod_thenLocalDate() {
assertEquals("2020-01-08", date.getTodaysDate());
}
@Test
public void whenUsingClock_thenLocalDate() {
assertEquals("2020-01-08", date.getTodaysDateFromClock());
}
@Test
public void givenValues_whenUsingZone_thenLocalDate() {
assertEquals("2020-01-08", date.getTodaysDateFromZone("Asia/Kolkata"));
}
@Test
public void givenValues_whenUsingOfMethod_thenLocalDate() {
assertEquals("2020-01-08", date.getCustomDateOne(2020, 1, 8));
}
@Test
public void givenValuesWithMonthEnum_whenUsingOfMethod_thenLocalDate() {
assertEquals("2020-01-08", date.getCustomDateTwo(2020, Month.JANUARY, 8));
}
@Test
public void givenValues_whenUsingEpochDay_thenLocalDate() {
assertEquals("2020-01-08", date.getDateFromEpochDay(18269));
}
@Test
public void givenValues_whenUsingYearDay_thenLocalDate() {
assertEquals("2020-01-08", date.getDateFromYearAndDayOfYear(2020, 8));
}
@Test
public void givenValues_whenUsingParse_thenLocalDate() {
assertEquals("2020-01-08", date.getDateFromString("2020-01-08"));
}
@Test
public void givenValuesWithFormatter_whenUsingParse_thenLocalDate() {
assertEquals("2020-01-08", date.getDateFromStringAndFormatter("8-Jan-2020", "d-MMM-yyyy"));
}
}