Commit ea0400c5 authored by R.W.Majeed's avatar R.W.Majeed
Browse files

utilize DateTimeFormatter for parsing of incomplete dates

parent 21e68406
package de.sekmi.histream;
import java.time.DateTimeException;
/*
* #%L
* histream
......@@ -22,9 +24,11 @@ package de.sekmi.histream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalUnit;
import java.util.Date;
......@@ -230,4 +234,54 @@ public class DateTimeAccuracy implements Temporal {
}
throw new UnsupportedOperationException("Timezone support not implemented yet");
}
/**
* Parse date time with a formatter.
*
* @param formatter formatter
* @param text input text
* @return date time with accuracy
*/
public static DateTimeAccuracy parse(DateTimeFormatter formatter, CharSequence text){
TemporalAccessor a = formatter.parse(text);
int year = a.get(ChronoField.YEAR);
// month
int month;
try{
month = a.get(ChronoField.MONTH_OF_YEAR);
}catch( DateTimeException e ){
return new DateTimeAccuracy(year);
}
int day;
try{
day = a.get(ChronoField.DAY_OF_MONTH);
}catch( DateTimeException e ){
return new DateTimeAccuracy(year,month);
}
int hour;
try{
hour = a.get(ChronoField.HOUR_OF_DAY);
}catch( DateTimeException e ){
return new DateTimeAccuracy(year,month,day);
}
int minute;
try{
minute = a.get(ChronoField.MINUTE_OF_HOUR);
}catch( DateTimeException e ){
return new DateTimeAccuracy(year,month,day, hour);
}
int seconds;
try{
seconds = a.get(ChronoField.SECOND_OF_MINUTE);
}catch( DateTimeException e ){
return new DateTimeAccuracy(year,month,day, hour, minute);
}
return new DateTimeAccuracy(year,month,day, hour, minute, seconds);
// milliseconds not supported for now
}
}
package de.sekmi.histream;
import java.text.ParsePosition;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
import org.junit.Assert;
import org.junit.Test;
public class TestDateTimeAccuracy {
@Test
public void testParseYYYYDD(){
//DateTimeAccuracy a = DateTimeAccuracy.parse(formatter, text)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M.u");
String text = "02.2003";
DateTimeAccuracy a = DateTimeAccuracy.parse(formatter, text);
Assert.assertEquals(ChronoUnit.MONTHS,a.getAccuracy());
Assert.assertEquals(2, a.get(ChronoField.MONTH_OF_YEAR));
Assert.assertEquals(2003, a.get(ChronoField.YEAR));
}
// TODO: further tests
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment