Reputation: 5487
If i have a string that contain a date in a format (unknown) "d/MM/YY" or "m:d:YYYY" etc.).
How could i parse it and get day,month,year values ?
I tried to parse them by filling an array with all format combinations , and try to parse the date with each one of them , i think it's a stupid solution !
Any ideas ?
Upvotes: 2
Views: 3888
Reputation: 65
//download library: org.ocpsoft.prettytime.nlp.PrettyTimeParser
String str = "2020.03.03";
Date date = new PrettyTimeParser().parseSyntax(str).get(0).getDates().get(0);
System.out.println(date)
Upvotes: 0
Reputation: 8387
Try to use this:
public static void main(String []args){
SimpleDateFormat dt = new SimpleDateFormat();
TimeZone date;
date = dt.getTimeZone();
Calendar cal = Calendar.getInstance().getInstance(Locale.UK);
cal.setTimeZone(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year);
System.out.println(month);
System.out.println(day);
}
Upvotes: 1
Reputation: 60184
If you unknown pattern format you can use something like this
DateTimeFormatter formatter1 = DateTimeFormat.forPattern("d/MM/YY")
.withLocale(Locale.UK);
DateTimeFormatter formatter2 = DateTimeFormat.forPattern("m:d:YYYY")
.withLocale(Locale.UK);
...
DateTimeFormatter formatterN = DateTimeFormat.forPattern(...
String stringDate = "08:18:2012";
LocalDate date;
try {
date = formatter1.parseLocalDate(stringDate);
} catch (Exception exp) {
try {
date = formatter2.parseLocalDate(stringDate);
} catch (Exception exp) {
...
date = formatterN.parseLocalDate(stringDate);
}
}
OR using List:
List<DateTimeFormatter> formatterList = new ArrayList<>();
formatterList.add(DateTimeFormat.forPattern("d/MM/YY")
.withLocale(Locale.UK));
formatterList.add(DateTimeFormat.forPattern("m:d:YYYY")
.withLocale(Locale.UK));
...
formatterList.add(DateTimeFormat.forPattern(...
String stringDate = "08:18:2012";
LocalDate date;
for(DateTimeFormatter formatter : formatterList) {
try {
return formatter.parseLocalDate(stringDate);
} catch (Exception exp) {
}
}
But it's impossible if you have pattern like "d/MM/YY" and "MM/d/YY", because you can recognize what string "01/01/15" means (where day and where month). Only if you have a lot of strings with one pattern you can statistically undestand what is day and what is month (month never be more then 12).
Upvotes: 1
Reputation: 5423
your best bet is to use natty
very useful library,
here is an example of how to use it:
public static Date parse(String date) throws Exception {
try{
List<DateGroup> parse = new PrettyTimeParser().parseSyntax(date);
return parse.get(0).getDates().get(0);
}catch (Exception e){
throw new Exception("unparseable date: " + date);
}
}
Upvotes: 3