Parse this date time string with regex - java

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;
}

Related

Put character in SimpleDateFormat

I want to validate the code of Date.
Input come from Textbox where user enters it.
and in code it will get calender's date instance and match it.
I want to put character in that SimpleDateFormat.
Code :
SimpleDateFormat formatter = new SimpleDateFormat("dd'ch' MMM, yyyy");
System.out.println("Date is :: " + formatter.format(Calendar.getInstance().getTime()));
String input = "20th Mar, 2014";
if(input.equals(formatter.format(Calendar.getInstance().getTime()))){
System.out.println("Matched");
}else{
System.out.println("Not Matched");
}
I want to put th, rd, st on place of ch in SDF.
means it will take input from user so it can be any date so I want some mechanism so only three will be placed at there.
Anyone knows that how can I do this ?
Help..
UPDATE
SimpleDateFormat formatterth = new SimpleDateFormat("dd'th' MMM, yyyy");
SimpleDateFormat formatterrd = new SimpleDateFormat("dd'rd' MMM, yyyy");
SimpleDateFormat formatternd = new SimpleDateFormat("dd'nd' MMM, yyyy");
SimpleDateFormat formatterst = new SimpleDateFormat("dd'st' MMM, yyyy");
String input = "20th Mar, 2014";
String input1 = "23rd Mar, 2014";
try {
if(input.equals(formatterth.parse(input1)) || input.equals(formatterrd.parse(input1)) || input.equals(formatternd.parse(input1)) || input.equals(formatterst.parse(input1))){
System.out.println("Matched");
}else{
System.out.println("Not Matched");
}
} catch (ParseException e) {
e.printStackTrace();
}
You can't, basically. You need three separate SimpleDateFormat objects:
new SimpleDateFormat("dd'st' MMM, yyyy")
new SimpleDateFormat("dd'nd' MMM, yyyy")
new SimpleDateFormat("dd'th' MMM, yyyy")
... then try parsing with each of them. Note that even this only works with ordinals in English... and it will parse "20st Mar, 2014" which possibly it shouldn't.
Ordinals in date formats are fundamentally a pain, and I haven't personally seen any API which deals with them nicely - partly because they're a pain in localization in general.
You can not do that with one Simple date format but you have to get Day from date check what kind of format you want to use.
Calendar cal = Calendar.getInstance();
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
SimpleDateFormat formatter;
if(dayOfMonth==1||dayOfMonth==21||dayOfMonth==31)
formatter = new SimpleDateFormat("dd'st'MMM, yyyy");
if dayOfMonth like 1,21,31 will use "dd'st' MMM YYYY" and so on.
One other way is try this...
String str="'th'";
String s="dd"+str+"MMM, yyyy";
SimpleDateFormat formatter = new SimpleDateFormat(str);
You can change str="'st'" and str="'rd'"
One more way come to my mind is By the use of method you just need ONE SimpleDate format
public String Method(String str)//pass"''th","'st'" or "'nd'"
{
SimpleDateFormat formatter = new SimpleDateFormat("dd"+str+"MMM, yyyy");
return formatter.format(Calendar.getInstance().getTime()).toString();
}
Try this method(ANS for your UPDATED Question):
public boolean CheckForST(String yourdate)
{
try {
SimpleDateFormat formatter2 = new SimpleDateFormat("dd'st' MMM, yyyy");
formatter2.parseObject(yourdate);
return true;
} catch (ParseException e) {
return false;
}
}
Which is only implemented for 'st' you can do the same for 'rd' or 'nd'

java.text.parseException:unparsable date

i am getting this error while i am trying to convert a string into date.
unparasable data
Below is my code:-
String str = "hello"
Second is missing at your parse String str. So, to parse it you should not include second format at SimpleDateFormat pattern. Also correct the day and Month format. Look at the declaration of df
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");//Remove :ss
To know details of pattern, go through this docs.
Edit
String date2 = sdformatter.format(date1);// format method return String.
//Should declare with String
Full Code
String str = "25-Nov-2013 06:00 AM";
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");//Remove :ss
SimpleDateFormat sdformatter = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss a");
Date date1=null;
try {
date1 = df.parse(str);
} catch (ParseException ex) {
ex.printStackTrace();
}
String date2 = sdformatter.format(date1);
System.out.println(date2);
According to str format you should write your SimpleDateFormat,
(25-Nov-2013 06:00 AM ---> dd-MMM-yyyy hh:mm a) and for
(25-Nov-2013 06:00:30 AM-----> dd-MMM-yyyy hh:mm:ss a)
will work
Try this
long newerdate = new Date().parse("25-Nov-2013 06:30 AM");
java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("dd-MM-yyyy hh:mm a");
String data = df.format(newerdate);
System.out.println(data);

SimpleDateFormat - Unparseable?

Take a look at my code:
try {
// String date = "30Jul2013";
SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyyyy", Locale.ENGLISH);
Date d = sdf.parse(date);
SimpleDateFormat nsdf = new SimpleDateFormat("MMMM dd, yyyy h:mm a", Locale.ENGLISH);
String nd = nsdf.format(d);
System.out.println(nd);
return nd;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Im am getting a error:
java.text.ParseException: Unparseable date: "2013-07-30 10:58:55.171"
at java.text.DateFormat.parse(DateFormat.java:337)
I would like to have an output of July 30, 2013 11:10 AM from the simpledateformat. There's LOCALE in my code. So what else should I do?
Thanks in advance!
try {
// String date = "30Jul2013";
SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyyyy", Locale.ENGLISH);
Date d = sdf.parse(date);
Your date String variable line is commented out, so who's to know what String you're parsing? -- the JVM that's who.
As Robert Harvey points out, the String that you're actually trying to parse is printed for you in the exception message. If you print that String before you parse you'll also see that it's not what you expect it is and that the compiler's right.
In sum, you are somehow expecting that your sdf SimpleDateFormat object is formatting a String of a format similar to "30Jul2013", but the JVM is telling you that this simply is not so, that the String you are trying to parse in fact looks nothing like this, but rather is "2013-07-30 10:58:55.171".

Checking date and its patten with expected pattern

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";

How to convert date format in java?

I have a String a ="   December 2011   ";
There is a before and after it.
How can I Convert it to: String b = "2011-12-1"
If this is really all there is to it, use .replace():
String b = a.replace(" ", "");
Unlike what its name would let you believe since .replaceAll() exists, .replace() will actually replace all occurrences. The difference is that .replaceAll() expects a string which will be compiled as a Pattern as an argument.
Use SimpleDateFormat.
new SimpleDateFormat("yyyy-MM-d").format(new SimpleDateFormat("MMMMM yyyy").parse(str));
String a = " Dezember 2011 ";
SimpleDateFormat sdf = new SimpleDateFormat("MMMMM yyyy");
a = a.replace(" ", "");
Date parse = sdf.parse(a);
SimpleDateFormat outSdf = new SimpleDateFormat("yyyy-MM-d");
String out = outSdf.format(parse);
System.out.println(out);
You use this code.It gives whatever you want to output.
You first remove &nbsp using replace function and after you have to just parse the your string.
try {
String a = " December 2011 ";
a = a.replace(" ", "");
SimpleDateFormat sdf = new SimpleDateFormat("MMMMM yyyy");
SimpleDateFormat SdfParser = new SimpleDateFormat("yyyy-MM-dd");
String date =SdfParser.format(sdf.parse(a));
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}

Categories

Resources