I have a date that keeps giving me an error of
java.text.ParseException: Unparseable date: " 5 April 2017 "
All other dates (without word months) work fine
The code I am using is below:
VisitDate=VisitDate.trim();
if (VisitDate.matches(".*[a-z].*")){
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
//Reformat the date the way I like it
SimpleDateFormat dt1 = new SimpleDateFormat("dd_MM_yy");
//Convert back into a string
try {
VisitDate=dt1.format(date);
if(VisitDate==null){
SimpleDateFormat dt2 = new SimpleDateFormat("dd MM yy");
//Convert back into a string
VisitDate=dt2.format(date);
if(VisitDate==null){
SimpleDateFormat dt3 = new SimpleDateFormat("dd MMMM yy");
//Convert back into a string
VisitDate=dt3.format(date);
if(VisitDate==null){
SimpleDateFormat dt4 = new SimpleDateFormat("d_MMM_yy");
//Convert back into a string
VisitDate=dt4.format(date);
if(VisitDate==null){
SimpleDateFormat dt5 = new SimpleDateFormat("d_MMMM_yy");
//Convert back into a string
VisitDate=dt5.format(date);
if(VisitDate==null){
SimpleDateFormat dt6 = new SimpleDateFormat("dd_MMM_yy");
//Convert back into a string
VisitDate=dt6.format(date);
if(VisitDate==null){
SimpleDateFormat dt7 = new SimpleDateFormat("dd_MMM_yyyy");
//Convert back into a string
VisitDate=dt7.format(date);
if(VisitDate==null){
SimpleDateFormat dt8 = new SimpleDateFormat("dd_MMMM_yyyy");
//Convert back into a string
VisitDate=dt8.format(date);
if(VisitDate==null){
VisitDate=VisitDate.replaceAll("\\s", "");
SimpleDateFormat dt9 = new SimpleDateFormat("dd MMMM yyyy");
//Convert back into a string
VisitDate=dt9.format(date);
}
}
}
}
}
}
}
}
} catch (Exception e) {
Logger.error(e+"->No visit Date frmo here with the original date as: "+date);
}
}
Happy to read your expressed interest in the modern date and time classes, here’s just a snippet to get you started:
String visitDate = " 5 April 2017 ";
DateTimeFormatter parseFormatter
= DateTimeFormatter.ofPattern("d MMMM uuuu", Locale.UK);
visitDate = visitDate.trim();
LocalDate date = LocalDate.parse(visitDate, parseFormatter);
// reformat to the string we like
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd_MM_uu");
visitDate = date.format(formatter);
The result is
05_04_17
I have spelled visitDate with a small v since the Java coding conventions recommend that variable names begin with a small letter.
The uu is subtle and probably something you can ignore. It’s a signed year where 0 equals 1 BC, -1 equals 2 BC and so forth. Assuming none of your dates are that old, you can use u and y interchangeably.
I believe that neither SimpleDateFormat.format() nor LocalDate.format() will ever return null, so all your null checks are superfluous.
Link for further reading: Oracle tutorial: Trail: Date Time
You only have one SimpleDateFormatter being used for parsing:
SimpleDateFormat changeDate = new SimpleDateFormat("dd_MMM_yy", Locale.UK);
//Convert the string to a date
Date date = changeDate.parse(VisitDate);
It is using the format dd_MMM_yy, however you are passing 4 digits for the year.
The rest of your SimpleDateFormatters are being used for formatting to a string, not parsing from a string. Only the first one will be called, since it will be able to produce a string given a valid date, and the following null checks will stop any other formatters from being used.
You have the input string to parse like this: " 5 April 2017 ". But you have no pattern match for this input
First please trim the space of input string
Second please change the format of your string or add another pattern to parse this string, because you have month April with 5 letter, but you have no pattern with MMMMM. Usually the month will be shorten to 3 letter like: April -> Apr, March -> Mar ...
Related
I am trying to take date in string and its input format string and converting the date in output format. However after conversion into Date, the java code increases the number of hours by one. I am not able to understand what causes the bug.
My Code:
try {
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
DateFormat inputFormat = new SimpleDateFormat(format);
Date date = inputFormat.parse(parameterValue);
parameterValue = outputFormat.format(date);
return parameterValue;
} catch (ParseException ex) {
// take action
}
format string: ddMMMyyyy / hh:mm z
Input Date: 07DEC2015 / 10:02 GMT
Output Date: 07/12/2015 11:02:00
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
resolved it.
If you don't want to use timezone, in java 8 you can use LocalDate/LocalTime/LocalDateTime:
LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
/*
Also check out ZoneDate, ZoneTime (for timezone)
Checkout - LocalDate, LocalTime
*/
This question already has answers here:
Java date is not preserving milliseconds in conversion with simple date format
(5 answers)
Closed 7 years ago.
Basically I'm attempting to parse date/time to Java, but having issues when trying to parse the milliseconds.
Example of data to be parsed: a[0] = 16/03/2015, a[1] = 10:00:18.120
I read in the two values and concatenate them.
Getting: dateTime = (java.lang.String) "16/03/2015 10:00:18.120"
As you can see the string has the milliseconds when i debug it. From here I parse it to SimpleDateFormat. It works- however the milliseconds are not displayed
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime;
dateTime= a[0]+" "+a[1];
Date d = df.parse(dateTime);
Current output: d = (java.util.Date) Mon Mar 16 10:00:18 GMT 2015
Thanks for your help.
Your code is fine, but not your interpretation of the result. As correctly mentioned in one comment, the method toString() of class java.util.Date does not output the millisecond part. But the millisecond part is still part of the state of your result object. Proof:
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime = "16/03/2015 10:00:18.120";
Date d = df.parse(dateTime);
System.out.println(d); // Mon Mar 16 10:00:18 CET 2015
System.out.println(d.getTime()); // 1426496418120
System.out.println("millisecond-part=" + (d.getTime() % 1000)); // millisecond-part=120
So all is fine. You can even format your result back to a string using the same (or another instance of SimpleDateFormat - maybe with different pattern, locale and timezone).
If java.util.Date was correctly implemented as value-type then the inventors of that class would have taken care of making the output of toString() representing the whole exact state of the object but it has not happened - another example why this class is broken.
Using DateFormat.format(Date date) function might meet your requirement
Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS",Locale.ENGLISH);
String dateTime;
dateTime=df.format(date);
String[] a=dateTime.split(" ");
System.out.println(a[0]+" "+a[1]);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS",Locale.ENGLISH);
String dateTime;
dateTime= "03/16/2015"+" "+"10:00:18.120";
Date d = df.parse(dateTime);
System.out.println(df.format(d));
Try this:
String[] a = new String[]{"16/03/2015", "10:00:18.120"};
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime = a[0] + " " + a[1];
try {
Date d = df.parse(dateTime);
System.out.println(d.getTime());//Returns milliseconds
} catch (ParseException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
The result: 1426492818120
I have this as a string 02/06/2012 1:25 PM EST
I want to use SimpleDateFormat to return "Feb" from that data
Here is what I tried
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
String month = "";
try {
month = gottenDate.format(gottenDate.parse("02/06/2012 1:25 PM EST"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Unfortunately gottenDate.parse("02/06/2012 1:25 PM EST") gets a parse exception when the SimpleDateFormat documents say it should work.
If I do SimpleDateFormat gottenDate = new SimpleDateFormat("MM"); with two M's instead of 3, it returns "02" for me, as expected. The documents say that 3 or more M's should return a textual month. This doesn't happen, why? And yes, by now I could have made a string array of months and matched them to the numberic month SDF returned for me, but I am curious.
How do I make it work for me, thank you!
Exception is expected in your case:
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
gottenDate.parse("02/06/2012 1:25 PM EST");
"gottenDate" is set up to parse a string if it matches "MMM" pattern. The following should work:
SimpleDateFormat gottenDate = new SimpleDateFormat("MMM");
gottenDate.parse("Feb");
Hopefully you can see what's going on here.
You need a format to parse the date: MM/dd/yyyy, and once you have a Date object from this first date format, you need a second one: MMM, to format the date as you want.
Formatting with MM will give you the month on two digits, and parsing with MMM will expect an abbreviated textual month, and won't parse 02.
You need two separate SimpeDateFormat instances with corresponding format strings to parse source date and format it back into short month form. Your format instance can't parse full date because it expecting only month in specified string.
SimpleDateFormat monthDate = new SimpleDateFormat("MMM");
SimpleDateFormat gottenDate = new SimpleDateFormat("dd/MM/yyyy h:mm a z");
String month = "";
try {
month = monthDate .format(gottenDate.parse("02/06/2012 1:25 PM EST"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Not sure about format of your source string, complex format strings are little tricky.
This is the code that will get MonthName to you:
public String getMonthName(String dtstr, String fmt) throws ParseException {
SimpleDateFormat gottenDate = new SimpleDateFormat(fmt);
SimpleDateFormat month = new SimpleDateFormat("MMM");
Date dt = gottenDate.parse(dtstr);
return month.format(dt);
}
Call it like this:
System.out.println(getMonthName("01/06/2012 1:25 PM EST"), "M/d/y");
OUTPUT:
Feb
Well, others were faster answering, but I think this will do what you want.
String date_str = "02/06/2012 1:25 PM EST";
SimpleDateFormat in_format = new SimpleDateFormat("MM/dd/yyyy h:mm aa zzz");
SimpleDateFormat out_format = new SimpleDateFormat("MMM");
Date my_date = in_format.parse(date_str);
String out_str = out_format.format(my_date);
System.out.println(out_str); // Prints Feb
Dates and times can get complicated because of the way people in different record times. The best reference I've found for understanding all this is here:
http://www.odi.ch/prog/design/datetime.php
Just to provide an alternative solution, since your jobs is to "extract" the month of a Date, I think Calendar best fits the job.
// Construct a Date object
final DateFormat df = new SimpleDateFormat("M/d/y");
final Date originalDate = df.parse("02/06/2012 1:25 PM EST");
final Calendar c = Calendar.getInstance();
c.setTime(originalDate); // set the calendar Date
// Extract the month
String month = c.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
System.out.println(month);
Earlier I posted the following question: How can I convert this date in Java?
But now I would like to know how I can convert this string into a date/time.
2010-03-15T16:34:46Z
For example: 03/15/10
UPDATED:
String pattern = "MM/dd/yy 'at' HH:mm";
Date date = new Date();
try {
date = new SimpleDateFormat(pattern).parse(q.getUpdated_at());
} catch (ParseException e) {
e.printStackTrace();
}
dateText.setText(new SimpleDateFormat("MM/dd/yy 'at' hh:mma").format(date));
Gives me a result like:
Mon Mar 15 16:34:50 MST 2010
How can I format it to be
03/15/10 at 4:34PM
?
Both SimpleDateFormat and joda-time DateTimeFormat can parse this, using this pattern:
String pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
For example:
Date date = new SimpleDateFormat(pattern).parse(dateString);
And (joda-time):
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
DateTime dateTime = dtf.parseDateTime(s);
Update
You have 2 date formats involved - one for parsing the input, and one for formatting the output. So:
dateText.setText(new SimpleDateFormat("MM/dd/yy 'at' hh:mma").format(date));
(Of course, for the sake of optimization, you can instantiate the SimpleDateFormat only once, and reuse it)
In a nutshell, you want to convert a date in a string format to a date in another string format. You have:
2010-03-15T16:34:46Z
and you want
03/15/10 at 4:34PM
You don't want to end up using java.util.Date object as you initially implied in your question. You also don't want to use its toString() since that returns a fixed format as definied in its javadoc.
The answer of Bozho still applies. Use java.text.SimpleDateFormat. First, you need to parse the date in string format into a Date object so that you can format it back into another string format.
// First parse string in pattern "yyyy-MM-dd'T'HH:mm:ss'Z'" to date object.
String dateString1 = "2010-03-15T16:34:46Z";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(dateString1);
// Then format date object to string in pattern "MM/dd/yy 'at' h:mma".
String dateString2 = new SimpleDateFormat("MM/dd/yy 'at' h:mma").format(date);
System.out.println(dateString2); // 03/15/10 at 4:34PM
If you want to format output string, change following line in your code
dateText.setText(date.toString());
to
dateText.setText(String.format("%1$tm/%1$td/%1$ty at %1$tl:%1$tM%1$Tp", date));
How can I take a string in a format such as: 2008-06-02 00:00:00.0 and convert it to: 02-Jun-2008?
Can I somehow take the original string, convert it to a Date object, then use a formatter to get the final output (rather than parsing the string myself)? Thanks!
You can use SimpleDateFormat to convert between a String and a Date object and vice versa based on a pattern. Click the API link, you'll see patterns being explained in detail. A 4-digit year can be represented with yyyy, a 3-character month abbreviation can be represented with MMM and so on.
First you need to parse the String of the first format into a Date object:
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = sdf1.parse(inputString);
Then you need to format the Date into a String of the second format:
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);
String outputString = sdf2.format(date);
Note that you need to take the Locale into account as well to get the month to be printed in English, else it will use the platform's default locale to translate the month.
Use 2 instances of SimpleDateFormat class. One for converting your input string to date and second to convert date back to string but in another format.
Here is an example of using SimpleDateFormat.
DateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
DateFormat endFormat = new SimpleDateFormat("dd-MM-yyyy");
String outputString = null;
try {
Date date = startFormat.parse(inputString);
outputString = endFormat.format(date);
} catch(ParseException pe) {
throw new IllegalArgumentException(inputString + " is not properly formated.", pe);
}
You can definitely use SimpleDateFormat class like others have recommended.
Another suggestion if it applies in your case. If you are getting this data from a sql query you can also use to_char() method to format it in the query itself. For example: to_char(column_name,'DD-MON-YYYY')