z11.samplestructs.DateParser Maven / Gradle / Ivy
/*
* Copyright 2017 vietduc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package z11.samplestructs;
/**
*
* @author vietduc
*/
public class DateParser {
public DateParser(String string_value) throws Exception {
string_value = string_value.replace(" ", " ");
String[] seperates = {"/", " ", "-", ".", ":", "\\"};
for (String seperate : seperates) {
try {
String[] values = string_value.split(seperate);
if (values.length == 3) {
day = Integer.parseInt(values[0].trim());
month = Integer.parseInt(values[1].trim());
year = Integer.parseInt(values[2].trim());
}
validData();
return;
} catch (Exception ex) {
}
}
throw new Exception("parsing error: " + string_value);
}
public DateParser(int day_, int month_, int year_) throws Exception {
day = day_;
month = month_;
year = year_;
validData();
}
@Override
public String toString() {
return "" + day + "/" + month + "/" + year;
}
private void validData() throws Exception {
if (day <= 0 || day >= 31) {
throw new Exception("day not valid: " + day);
}
if (month <= 0 || month >= 13) {
throw new Exception("day month valid: " + month);
}
if (year <= 1970 || year >= 2050) {
throw new Exception("year not valid: " + year);
}
}
public int day;
public int month;
public int year;
public static void main(String[] args) throws Exception {
DateParser p = new DateParser("17-9-1991");
System.out.println(p.toString());
}
}