User will enter the Date like yyyy-MM-dd
or yyyy-MM-dd hh:mm:ss
.Then I need to validate the timestamp. please help me on this.
I need to verify these type of validations of Both (yyyy-MM-dd) or (yyyy-MM-dd hh:mm:ss). If the user enters the date is yyyy-MM-dd then will take the like this yyyy-MM-dd 00:00:00 and else if user enters the date is yyyy-MM-dd HH:mm:ss then take as it is like yyyy-MM-dd HH:mm:ss
private static boolean dateValidate(String inputDate) {
try {
String[] datePattern = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd "};
for (String pattern : datePattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = sdf.parse(inputDate);
String formattedDate = sdf.format(date);
if (inputDate.equals(formattedDate)) {
return true;
}
}
} catch (ParseException ex) {
return false;
}
return false;
}
public static void main(String args[]) {
// TODO Auto-generated method stub
System.out.println(SampleTest.dateValidate("2014-02-22 22:23:22"));
System.out.println(SampleTest.dateValidate("2014-02-22"));
}
String[] formatStrings = { "yyyy-MM-dd hh:mm:ss", "yyyy-MM-dd" };
for (String formatString : formatStrings) {
try {
Date date = new SimpleDateFormat(formatString).parse(<Your Input date here>);
System.out.println(date.toString());
break;
} catch (ParseException e) {
System.out.println("ex");
}
}
Note: the order of the String array (formatStrings) is important. Some times "yyyy-MM-dd" can parse the other date formats also.
Try this code
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the date");
String inputDate = sc.nextLine();
if(dateValidate(inputDate)){
System.out.println("Input Date is in correct pattern");
}
else{
System.out.println("Input date is in wrong pattern");
}
}
private static boolean dateValidate(String inputDate) {
try {
String[] datePattern = {"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd"};
for (String pattern : datePattern) {
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date date = sdf.parse(inputDate);
String formattedDate = sdf.format(date);
if (inputDate.equals(formattedDate)) {
return true;
}
}
} catch (ParseException ex) {
return false;
}
return false;
}
If you just want to validate them try regex for it
System.out.println(Pattern.matches
("^((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$","2011-12-31"));
System.out.println(Pattern.matches
("((19|20)\\d\\d)-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])
([2][0-3]|[0-1][0-9]|[1-9]):[0-5][0-9]:([0-5][0-9]|[6][0])$","2014-02-22 23:33:32"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.