I have a date and it's supposed pattern in string.
//True
String date ="2012-10-12 12:01:10.10.150";
String pattern = "yyyy-MM-dd hh:mm:ss.SSS";
//False
String date ="2012-10-12 12:01:10.150";
String pattern = "yyyy-MM-dd hh:mm:ss";
Now,i wanted to know whether the date variable has a proper date which satisfies a given pattern in string. In the above example True/False which I shows is the expected result.
I have tried with SimpleDateFormat(if it throws ParseException),but it will not going to work for 2nd example.
public boolean isValidDate(String date, String pattern) {
if (date == null)
return false;
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
try {
dateFormat.parse(date.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
I think you need to use both regex and SimpleDateFormat to achieve what you want
boolean validate(String date, String pattern) throws ParseException {
String regex = pattern.replaceAll("\\w", "\\\\d").replace(".", "\\.");
if (!date.matches(regex)) {
return false;
}
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
sdf.setLenient(false);
try {
sdf.parse(date);
} catch (Exception e) {
return false;
}
return true;
}
Use yyyy-MM-dd hh:mm:ss as the pattern for the second date.
String date = "2012-10-12 12:01:10";
String pattern = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
Date parse = sdf.parse(date);
The capital S stands for milliseconds which your second string doesn't have. See the API.
From the SimpleDateFormat.parse() Java doc:
...parsing does not necessarily use all characters up to the end of the
string...
This means if your date is longer that the pattern it will still produce a valid Date instance. The other way around (e.g. your second example) the pattern is longer (more detailed) that the given date string, hence it doesn't produce a Date. Use this instead for your second example:
String pattern = "yyyy-MM-dd hh:mm:ss";
Related
So I have the following string containing a date and time, which I need to parse
« by username on September 13, 2015, 08:34:02 am »
I have the following expression which seems to work in rubular.com but Java only collects September from it.
I would also like to have two groups, the date and the time. How can I do this?
January|February|March|April|May|June|July|August|September|October|November|December| [0-9]{2}, [0-9]{4}, [0-9]{2}:[0-9]{2}:[0-9]{2} am|pm
Thanks
One could try something like this
String in = "by username on September 13, 2015, 08:34:02 am";
//date parsing pattern
String s = "MMM d, yyyy, HH:mm:ss aaa";
SimpleDateFormat sdf = new SimpleDateFormat(s, Locale.US);
try {
//pattern to get rid of 'by username on'
String p = "\\w+\\s\\w+\\s\\w+\\s";
Date d = sdf.parse(in.replaceFirst(p, ""));
System.out.println(d);
} catch (ParseException e) {
e.printStackTrace();
}
Try this one.
((?:January|February|March|April|May|June|July|August|September|October|November|December)\s[0-9]{2},\s[0-9]{4}),\s([0-9]{2}:[0-9]{2}:[0-9]{2}\sam|pm)
Tested on your expression, it captures both date and time into separate groups.
If the date is always entered in exactly the same format you could use a function like the following. If you expect more spaces between the parts, then add \s+ (escaped as \\s+ in Java string).
public static Date findAndParseDate(String s) {
Date parsedDate = null;
String patternStr = "((January|February|March|April|May|June|July|August|September|October|November|December) [0-9]{2}, [0-9]{4}, [0-9]{2}:[0-9]{2}:[0-9]{2} am|pm)";
Pattern p = Pattern.compile(patternStr);
Matcher m = p.matcher(s);
if (m.find()) {
String extractedDateTimePart = m.group(1);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM dd, yyyy, hh:mm:ss aa");
try {
parsedDate = simpleDateFormat.parse(extractedDateTimePart);
} catch (Exception ex) {
}
}
return parsedDate;
}
I am writing a converter method that would parse an xml string data to java objects. But i am not able to parse dates to date objects.
How to format this date string "2013-08-26T12:00:00.000" in the following way: "2013-08-26 12:00:00" to Date object in java?
Edited to add the below code snippet.
Here is what I tried to do.
public Object fromString(String str) {
DateFormat dateFormat = DateFormat.getDateInstance();
try {
Date date = dateFormat.parse(str);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
}
You should google these things first.
Here you go:
public static void main(String[] args) {
String inFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS";
String outFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(inFormat);
try {
Date d = sdf.parse("2013-08-26T12:00:00.000");
sdf.applyPattern(outFormat);
System.out.println(sdf.format(d));
} catch (ParseException e) {
// handle appropriately
e.printStackTrace();
}
}
You can parse any Date-like string to Date object (as long as the the string represents a valid date) using http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
There is no point in re-formatting the String.
In order to process XML-date-time-strings which are allowed to be of variable precision (sometimes leaving out second- or fraction-part or timezone-offset) the use of SimpleDateFormat is not a good option because then you would only have one pattern. Not flexible.
Alternative for XML:
String xml = "2013-08-26T12:00:00.000"; // maybe optionally with additional timezone offset
javax.xml.datatype.DatatypeFactory factory = javax.xml.datatype.DatatypeFactory.newInstance();
XMLGregorianCalendar xmlGregCal = factory.newXMLGregorianCalendar(xml);
java.util.Date d = xmlGregCal.toGregorianCalendar().getTime();
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String output = outputFormat.format(d);
Watch also out for some overloaded methods to change the timezone settings for parsing and formatting - see the javadoc.
You may try this:
public static void main(String[] args) throws Exception {
String original = "2013-08-26T12:00:00.000";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S").parse(original);
String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.printf("Before: %s\nAfter: %s\n", original, format);
}
OUTPUT:
Before: 2013-08-26T12:00:00.000
After: 2013-08-26 12:00:00
I want to check if a String is in certain pattern.
for example i want to check is a String matches the pattern: 2012-02-20.
I.E: xxxx-xx-xx when x is a number.
Is it possible? someone said regular expressions.
use this regex \d{4}-\d{2}-\d{2}
for checking use:
yourString.matches(regexString);
if you want to test if the date string is a valid date, better use SimpleDateFormat to check. don't use regex for that validation, how about month is 13? date is 50? leap years?
some example:
public boolean isValidDate(String dateString) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
df.parse(dateString);
return true;
} catch (ParseException e) {
return false;
}
}
You can do that with the SimpleDateFormat parse method:
final SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
boolean matchesDateFormat(String date)
{
try
{
format.parse(date);
return true;
}
catch(ParseException e)
{
return false;
}
}
Of course, if you later go on to parse the date anyway then you can skip this and just try to parse it.
You can check that the String follow the exact format of 4 digits, a dash -, 2 digits, a dash - and 2 digits with #burning_LEGION's regex. However, it doesn't check whether the String represents a valid date. You can specify 9999-99-99 and it will pass the validation.
Using SimpleDateFormat is the proper method to check that the String is a valid date and it follows a given format of representation. SimpleDateFormat, apart from formatting a date, can also be used to parse Date from String: parse(String), parse(String, ParsePosition).
By default, SimpleDateFormat is lenient, which means it will allow nonsensical dates such as 2013-025-234 to pass. Use setLenient(boolean lenient) to false will solve this problem.
However, another problem is that it will also ignore any garbage data that is after a valid date (e.g. 2012-03-23garbage#$%$#%). Setting lenient doesn't solve this problem. We need to check the last position with parse(String, ParsePosition) method.
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
// Make the parsing strict - otherwise, it is worse than regex solution
dateFormatter.setLenient(false);
Date date = null;
ParsePosition pos = new ParsePosition(0);
date = dateFormatter.parse(inputString, pos);
if (date != null && pos.getIndex() == inputString.length()) {
// These 3 points are ensured:
// - The string only contains the date.
// - The date follows the format strictly.
// - And the date is a valid one.
} else {
// Valid date but string contains other garbage
// Or the string has invalid date or garbage
}
SimpleDateFormat will allow 2013-1-5 to pass, which I think is a reasonable leniency. If you don't want this, you can do a check against the regex before plugging the String into the parse method.
You can check following code:
public void test() {
String REG_EXP = "(\\d{4}-[0,1]?\\d{1}-[0,1,2,3]?\\d{1})"; //yyyy-mm-dd formate this can not check boundary condition something like this... 1981-02-30
String REG_EXP1 = "(\\d{4}-\\d{2}-\\d{2})"; // if u just want xxxx-xx-xx where x is number
String input = "date1 1981-09-06 wrong date 9999-22-22 date2 1981-9-09 date3 1981-11-1 date4";
Pattern pattern = Pattern.compile(REG_EXP);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
I want to create a method to validate a date by using SimpleDateFormat.
If the date is valid(e.g. 02/09/2012 or 2/09/2012 or 02/9/2012), this method should return true.
But if the format of the date is wrong(e.g. 02/09/201X) or logically wrong(e.g. 32/09/2012), this method should return false.
I try to write this method like this:
private boolean isValidDate(String date) {
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
DateFormat df2 = new SimpleDateFormat("d-MM-yyyy");
DateFormat df3 = new SimpleDateFormat("dd-M-yyyy");
Date d = null;
String s = null;
try {
d = df1.parse(date);
}catch (Exception e1) {
try{
d = df2.parse(date);
}catch (Exception e2) {
try {
d= df3.parse(date);
}catch (Exception e3) {
return false;
}
s = df3.format(d);
return date.equals(s);
}
s = df2.format(d);
return date.equals(s);
}
s = df1.format(d);
return date.equals(s);
}
But if I validate a date, for instance, 2/09/2012, it returns false (actually it should return true). I have no idea why... Can anyone find what's the problem with my code, or this logic is totally wrong? Is there any better way to do this validation?
Your input is in the format 2/09/2012 not 2-09-2012, so your dateformat should be like below:
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2 = new SimpleDateFormat("d/MM/yyyy");
DateFormat df3 = new SimpleDateFormat("dd/M/yyyy");
I think your code is fine (but not very scalable - try to do it in a for-loop in case you add more formats later).
The problem is that your format strings are wrong. Instead of dd-MM-yyyy you should have dd/MM/yyyy. The same goes for the rest of the formats:
DateFormat df1 = new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2 = new SimpleDateFormat("d/MM/yyyy");
DateFormat df3 = new SimpleDateFormat("dd/M/yyyy");
The validation fails because / isn't -.
Add this additional check after parsing each string:
Tokenize the value of the date String
Then use the extracted day, month and year values to create a new Date object using GregorianCalendar
Compare this to the date object you created from parsing the date strings
If they match then you know that the input string contained a valid date format
I have two strings, the first one contains an actual date, and the second one contains a date format.
I want to compare both the strings. Here is my code:
String s1 = "01/02/2012";
String s2 = "dd/MM/yyyy";
if (s1.equalsIgnoreCase(s2)){
System.out.println("true");}
else {
System.out.println("false");}
I have tried with all the string methods (like compare(), equalTo(), etc.). It's always executing the else part, i.e. the condition is always "false".
Check Using Format
if(isValidDate("01/02/2012")){
System.out.println("true");}else{
System.out.println("false");}
}
public boolean isValidDate(String inDate) {
if (inDate == null)
return false;
// set the format to use as a constructor argument
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
if (inDate.trim().length() != dateFormat.toPattern().length())
return false;
dateFormat.setLenient(false);
try {
// parse the inDate parameter
dateFormat.parse(inDate.trim());
} catch (ParseException pe) {
return false;
}
return true;
}
// date validation using SimpleDateFormat
// it will take a string and make sure it's in the proper
// format as defined by you, and it will also make sure that
// it's a legal date
public boolean isValidDate(String date)
{
// set date format, this can be changed to whatever format
// you want, MM-dd-yyyy, MM.dd.yyyy, dd.MM.yyyy etc.
// you can read more about it here:
// http://java.sun.com/j2se/1.4.2/docs/api/index.html
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
// declare and initialize testDate variable, this is what will hold
// our converted string
Date testDate = null;
// we will now try to parse the string into date form
try
{
testDate = sdf.parse(date);
}
// if the format of the string provided doesn't match the format we
// declared in SimpleDateFormat() we will get an exception
catch (ParseException e)
{
errorMessage = "the date you provided is in an invalid date" +
" format.";
return false;
}
// dateformat.parse will accept any date as long as it's in the format
// you defined, it simply rolls dates over, for example, december 32
// becomes jan 1 and december 0 becomes november 30
// This statement will make sure that once the string
// has been checked for proper formatting that the date is still the
// date that was entered, if it's not, we assume that the date is invalid
if (!sdf.format(testDate).equals(date))
{
errorMessage = "The date that you provided is invalid.";
return false;
}
// if we make it to here without getting an error it is assumed that
// the date was a valid one and that it's in the proper format
return true;
} // end isValidDate
Do it as below:
String s1 = "01/02/2012";
String s2 = "dd/MM/yyyy";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(s2);
try {
Date date = simpleDateFormat.parse(s1);
System.out.println(simpleDateFormat.format(date));
System.out.println("Parse successful. s1 matches with s2");
} catch (ParseException e) {
System.out.println("Parse failed. s1 differs by format.");
}
Please Note: a little warning
if you have s1="01/13/2012" parse will get successful, albeit it is not correct, because it will consider it as "01/01/2013" instead. So if you are ok with this, then proceed, else go ahead with your own implementation.