Skip to content

Instantly share code, notes, and snippets.

@hjonck
Last active October 5, 2017 15:22
Show Gist options
  • Save hjonck/66e5e194b709c663549632fa21844be3 to your computer and use it in GitHub Desktop.
Save hjonck/66e5e194b709c663549632fa21844be3 to your computer and use it in GitHub Desktop.
Play with Java 8 Dates, new time API and catching invalid dates, getting the first Sunday in each Month
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.sql.*;
import java.time.*;
import static java.time.temporal.TemporalAdjusters.*;
public class Main {
public static Date isValidDate(String inDate, String formatString) {
Date dateTime = null;
SimpleDateFormat dateFormat = new SimpleDateFormat(formatString);
dateFormat.setLenient(false);
try {
dateTime = dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
System.out.println(pe.getMessage());
return null;
}
return dateTime;
}
public static Date getFirstSundayInMonth(Date date) {
// Time Zone
ZoneId defaultZoneId = ZoneId.systemDefault();
System.out.println("System Default TimeZone : " + defaultZoneId);
//1. Convert Date -> Instant
Instant instant = date.toInstant();
System.out.println("instant : " + instant);
//2. Instant + system default time zone + toLocalDate() = LocalDate
LocalDate localDate = instant.atZone(defaultZoneId).toLocalDate();
System.out.println("localDate : " + localDate);
LocalDateTime firstSundayOfMonth = LocalDateTime
.ofInstant(date.toInstant(), ZoneId.systemDefault())
.with(firstDayOfMonth())
.with(nextOrSame(DayOfWeek.SUNDAY));
System.out.println("First Sunday: " + firstSundayOfMonth);
instant = firstSundayOfMonth.atZone(ZoneId.systemDefault()).toInstant();
Date newDateTime = Date.from(instant);
return newDateTime;
}
public static void main(String[] args) {
System.out.println(isValidDate("2004-02-29","yyyy-MM-dd"));
System.out.println(isValidDate("2005-02-29","yyyy-MM-dd"));
System.out.println(isValidDate("2005-04-31","yyyy-MM-dd"));
System.out.println(isValidDate("31/04/2005","dd/MM/yyyy"));
System.out.println(isValidDate("31/03/2005","dd/MM/yyyy"));
Date dateTime,dateTime1, dateTime2,dateTime3;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
dateTime = dateFormat.parse("2005-04-31");
dateTime1 = dateFormat.parse("2017-10-31");
dateTime2 = dateFormat.parse("2017-10-2");
dateTime3 = dateFormat.parse("2017-11-5");
} catch (ParseException pe) {
System.out.println(pe.getMessage());
return;
}
getFirstSundayInMonth(dateTime);
getFirstSundayInMonth(dateTime1);
getFirstSundayInMonth(dateTime2);
getFirstSundayInMonth(dateTime3);
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment