I am trying to create a method which converts DAY, MONTH, YEAR to Date object in Java
I have
String DAY = "31"
String YEAR = "2012"
String MONTH = "11"
I need a configurable Format as output.
String format = "MM/dd/yyy";
I will always get DAY string from "01" to "31" only
I will always get YEAR string from "1000" to "9999" only
I will always get MONTH string from "01" to "12" only (Never get Jan, Feb etc)
I understand that SimpleDateFormat(format) can work up to some extend.
new SimpleDateFormat("MM/dd/yyyy") will parse "02/01/2010" as Feb 01 2010 but
new SimpleDateFormat("mm/dd/yyyy") will parse "02/01/2010" as Jan 01 2010
Is it possible to write a generic method in java which converts given Strings (DAY, MONTH, YEAR) to Date object based on a configurable pattern?? and which can throw exception is I supply a wrong combination of DAY, MONTH, YEAR (like DAY = "31", MONTH = "02", YEAR = "2010")
Something like :
Date dateParser(String format){
String DAY = "01";
String YEAR = "1922";
String MONTH = "02";
return date;
}
SimpleDateFormat
will do what you need.mm/dd/yyyy
doesn't work because lowercasemm
is for minutes not months. – GriffeyDogjava.util
date-time API andSimpleDateFormat
. – Arvind Kumar AvinashDate
norSimpleDateFormat
. Those classes are poorly designed and long outdated, the latter in particular notoriously troublesome. Instead useLocalDate
andDateTimeFormatter
, both from java.time, the modern Java date and time API. – Ole V.V.Date
anymore. It's outdated, having several problems and not anymore recommended to be used. Use, instead,LocalDateTime
API (which also includesZonedDateTime
,LocalDate
andLocalTime
). – Giorgi Tsiklauri