forcing 4 digits year in java's simpledateformat - java

I want to validate and parse dates using a simpleDateFormat with the format "yyyymmdd"
This also allows 100624, which is parsed to the year 10 (54 years after Julius Ceasar died). The dates will also be something like 1970, so I don't want to settle with SimpleDateFornat("yymmdd").
I'm wondering is there a way to force a four digit year format using the SimpleDateFormat? I'm close to do a regexp test upfront but maybe there is a smart way to use the (Simple)DateFormat()?
As requested the code, things are getting more complicate and my research was half. The Format used was yyyy-MM-dd to start with (it came from a variable, which had a wrong javadoc). However as indicated in an answer below yyyyMMdd does force a four year digit. So my question is changed to How to force a four digit year for the "yyyy-MM-dd" format. And why does "yyyyMMdd" behave different?
public void testMaturity() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
System.out.println(" " + sdf.format(sdf.parse("40-12-14")));
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
sdf.setLenient(false);
System.out.println(" " + sdf2.format(sdf2.parse("401214")));
fail();
} catch (ParseException pe) {
assertTrue(true);
}
Which prints 0040-12-14

Simply use yyyyMMdd (note: upper case M is used to indicate month, otherwise you're parsing minutes!) and then check if the year is greater some cutoff date (for example, when parsing birth dates, greater 1800 is a safe bet, when parsing dates for upcomming dates greater than or equal the current year would be good).

Hmm. I suspect you should be using "MM" instead of "mm" to start with... but "100624" doesn't parse anyway when I try it - even in lenient mode:
import java.util.*;
import java.text.*;
public class Test
{
public static void main(String[] args) throws Exception
{
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
format.setLenient(true);
tryParse(format, "100624");
format.setLenient(false);
tryParse(format, "100624");
}
static void tryParse(DateFormat format, String text)
{
try
{
Date date = format.parse(text);
System.out.println("Parsed " + text + " to " + date);
}
catch (ParseException pe)
{
System.out.println("Failed to parse " + text);
}
}
}
(And even using "mm" instead of "MM" it still fails to parse.)
Prints:
Failed to parse 100624
Failed to parse 100624
Perhaps you could show the code which is managing to parse this?

There is no easy way for this. If you're saying that dates can be like 1970 the main question would be what 700624 means - 1970 or 2070? You should either implement some cutoff date like Joachim proposed or move entirely to 4 digits year.

Well it is quite straight and forward. Follow these simple steps:
Step 1:
try {
String dates = "40-12-14";
String patterns = "yy-MM-dd";
SimpleDateFormat format3 = new SimpleDateFormat(patterns);``
java.util.Date dates1 = format3.parse(dates);
SimpleDateFormat sdfDates = new SimpleDateFormat("dd/MM/yyyy");
String strDate1 = sdfDate.format(dates1);
System.out.println("Date1: " + strDate1);
}
catch(ParseException e){
e.printStackTrace();
}
This will output:
Date1: 14/12/1940

Related

Dateformatter in java [duplicate]

This question already has answers here:
SimpleDateFormat parsing date with 'Z' literal [duplicate]
(12 answers)
Closed 4 years ago.
I am using the below code to format millisecond resolution date strings. It works for 2018-09-14T13:05:21.329Z but not 2018-09-14T13:05:21.3Z. Can anybody suggest the reason and how to correct it?
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date parsedDate = formatter.parse(date);
String destDate = sdfDestination.format(parsedDate);
return destDate;
} catch (java.text.ParseException parseException) {
logger.error("Parse Exception occured while converting publication time to date "
+ "format 'yyyy-MM-dd HH:mm:ss'", parseException);
}
I get below exception:
java.text.ParseException: Unparseable date: "2018-09-14T13:05:21.3Z"
at java.text.DateFormat.parse(Unknown Source) ~[na:1.8.0_181]
at com.noordpool.api.implementation.utility.Utility.parseDate(Utility.java:136) [classes/:na]
at com.noordpool.api.implementation.utility.Utility.parseMessage(Utility.java:77) [classes/:na]
Your only problem is that you are using a wrong pattern for SimpleDateFormat, you need to change:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
To:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Because the Z used in the date string means "zero hour offset" so you just need to pass it as 'Z' in your pattern.
This is a working demo with the right pattern.
Edit:
And to make things work with different Locales and Timezones, you need to use the appropriate Locale when you are creating the SimpleDateFormat instance, this is how should be the code:
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
The only possible issue I can see is that you're passing in milliseconds incorrectly and the program doesn't know what to do about it.
So the last part of the formatter indicates with milliseconds and a timezone as .SSSX
But how does it evaluate 3Z for the input into this? I mean, do you say it's 300 timezone Z, or say it's 003 timezone Z, or worse, try and parse it as 3Z, which hopefully you see that you cannot turn '3Z' into a number.
To remedy this, I'd validate your input 'date' and ensure the milliseconds part is always 3 digits long, this removes the ambiguity and the program always knows that you mean '300 milliseconds, timezone Z'.
There is a problem in java 8 where the number of characters that you specified with the formatter should be an exact match (which is not specified in the documentation).
You can use three different Formatters and use nested exception as follows:
DateFormat format1 = new SimpleDateFormat("y-M-d'T'H:m:s.SX");
DateFormat format2 = new SimpleDateFormat("y-M-d'T'H:m:s.SSX");
DateFormat format3 = new SimpleDateFormat("y-M-d'T'H:m:s.SSSX");
Date parsedDate;
try {
// Parsing for the case - 2018-09-14T13:05:21.3Z
parsedDate = format1.parse(date);
} catch (ParseException e1) {
try {
// Parsing for the case - 2018-09-14T13:05:21.32Z
parsedDate = format2.parse(date);
} catch (ParseException e2) {
try {
// Parsing for the case - 2018-09-14T13:05:21.329Z
parsedDate = format3.parse(date);
} catch (ParseException e2) {
//The input date format is wrong
logger.error("Wrong format for date - " + date);
}
}
}
java.time
DateTimeFormatter dtfDestination
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
String date = "2018-09-14T13:05:21.3Z";
String destDate = Instant.parse(date)
.atZone(ZoneId.of("Indian/Comoro"))
.format(dtfDestination);
System.out.println(destDate);
Output from this snippet is:
2018-09-14 16:05:21
Please substitute your correct time zone if it didn’t happen to be Indian/Comoro, since correct output depends on using the correct time zone. If you want to use your JVM’s default time zone, specify ZoneId.systemDefault(), but be aware that the default can be changed at any time from other parts of your program or other programs running in the same JVM.
I am exploiting the fact that your string, "2018-09-14T13:05:21.3Z", is in ISO 8601 format, the format that the classes of java.time parse as their default, that is, without any explicit formatter. Instant.parse accepts anything from 0 through 9 decimals on the seconds, so there is no problem giving it a string with just 1 decimal, as you did. In comparison there is no way that an old-fashioned SimpleDateFormat can parse 1 decimal on the seconds with full precision since it takes pattern letter (uppercase) S to mean milliseconds, so .3 will be parsed as 3 milliseconds, not 3 tenths of a second, as it means.
Jahnavi Paliwal has already correctly diagnosed and explained the reason for the exception you got.
The date-time classes that you used, DateFormat, SimpleDateFormat and Date, are all long outdated and SimpleDateFormat in particular is notoriously troublesome. Since you seem to be using Java 8 (and even if you didn’t), I suggest you avoid those classes completely and use java.time instead.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601

String to Date Conversion mm/dd/yy to YYYY-MM-DD in java [duplicate]

This question already has answers here:
Java Date Error
(8 answers)
Closed 4 years ago.
I want to convert String values in the format of mm/dd/yy to YYYY-MM-DD Date. how to do this conversion?
The input parameter is: 03/01/18
Code to convert String to Date is given below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
When tried to convert using this method it shows the following error
java.text.ParseException: Unparseable date: "03/01/18"
As you say the input is in a different format, first convert the String to a valid Date object. Once you have the Date object you can format it into different types , as you want, check.
To Convert as Date,
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
date = formatter.parse(dateVlaue);
To Print it out in the other format,
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date)
You are writing it the wrong way. In fact, for the date you want to convert, you need to write
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
The format you are passing to SimpleDateFormat is ("yyyy-MM-dd") which expects date to be in form 2013-03-01 and hence the error.
You need to supply the correct format that you are passing your input as something like below
public static Date stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yy");
try {
date = formatter.parse(dateVlaue);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
The solution for the above problem
Convert the String date value in the Format of "dd/mm/yy" to Date.
By using the converted Date can able to frame the required date format.
The method has given below
public static String stringToDateLinen(String dateVlaue) {
Date date = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yy");
String dateString = null;
try {
// convert to Date Format From "dd/mm/yy" to Date
date = formatter.parse(dateVlaue);
// from the Converted date to the required format eg : "yyyy-MM-dd"
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
dateString = formatter1.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return dateString;
}
EDIT: Your question said “String values in the format of mm/dd/yy”, but I understand from your comments that you meant “my input format is dd/mm/yy as string”, so I have changed the format pattern string in the below code accordingly. Otherwise the code is the same in both cases.
public static Optional<LocalDate> stringToDateLinen(String dateValue) {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yy");
try {
return Optional.of(LocalDate.parse(dateValue, dateFormatter));
} catch (DateTimeParseException dtpe) {
return Optional.empty();
}
}
Try it:
stringToDateLinen("03/01/18")
.ifPresentOrElse(System.out::println,
() -> System.out.println("Could not parse"));
Output:
2018-01-03
I recommend you stay away from SimpleDateFormat. It is long outdated and notoriously troublesome too. And Date is just as outdated. Instead use LocalDate and DateTimeFormatter from java.time, the modern Java date and time API. It is so much nicer to work with. A LocalDate is a date without time of day, so this suites your requirements much more nicely than a Date, which despite its name is a point in time. LocalDate.toString() produces exactly the format you said you desired (though the LocalDate doesn’t have a format in it).
My method interprets your 2-digit year as 2000-based, that is, from 2000 through 2099. Please think twice before deciding that this is what you want.
What would you want to happen if the string cannot be parsed into a valid date? I’m afraid that returning null is a NullPointerException waiting to happen and a subsequent debugging session to track down the root cause. You may consider letting the DateTimeParseException be thrown out of your method (just declare that in Javadoc) so the root cause is in the stack trace. Or even throw an AssertionError if the situation is not supposed to happen. In my code I am returning an Optional, which clearly signals to the caller that there may not be a result, which (I hope) prevents any NullPointerException. In the code calling the method I am using the ifPresentOrElse method introduced in Java 9. If not using Java 9 yet, use ifPresent and/or read more about using Optional elsewhere.
What went wrong in your code?
The other answers are correct: Your format pattern string used for parsing needs to match the input (not your output). The ParseException was thrown because the format pattern contained hyphens and the input slashes. It was good that you got the exception because another problem is that the order of year, month and day doesn’t match, neither does the number of digits in the year.
Link
Oracle tutorial: Date Time explaining how to use java.time.

Is DateTimeFormatter more strict than SimpleDateFormat? Parsing date with milliseconds

I have simple test case:
public static void main(String[] args) {
String pattern = "yyyy-MM-dd HH:mm:ss.SSS";
String date = "2017-01-15 15:15:15.5";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
FastDateFormat fastDateFormat = FastDateFormat.getInstance(pattern);
try {
System.out.println("SFD: " + simpleDateFormat.parse(date));
}catch (Exception e) {
System.err.println("SDF failed");
}
try {
System.out.println("DTF: " + dateTimeFormatter.parse(date));
}catch (Exception e) {
System.err.println("DTF failed");
}
try {
System.out.println("FDF: " + fastDateFormat.parse(date));
}catch (Exception e) {
System.err.println("FDF failed");
}
}
Output is like this:
SFD: Thu Jan 15 15:15:15 CET 1970
DTF failed
FDF: Thu Jan 15 15:15:15 CET 1970
According to the results, Java's 8 DateTimeFormatter is more strict then SimpleDateFormat. My question is why and in that case, what would be best approach to accept both dates with .S as millis or .SSS, like parsing multiple times with try/catch ?
SimpleDateFormat's is not strict per default, because the property lenient is true per default. But you can set the property lenient to false to make it strict.
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
simpleDateFormat.setLenient(false);
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
try {
System.out.println("SFD: " + simpleDateFormat.parse(date));
} catch (Exception e) {
System.err.println("SDF failed");
}
try {
System.out.println("DTF: " + dateTimeFormatter.parse(date));
} catch (Exception e) {
System.err.println("DTF failed");
}
The result will be then
SDF failed
DTF failed
See DateFormat.parse(String, ParsePosition)
By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).
You are basically asking why SimpleDateFormat accepts one digit millisecond values when the pattern says ".SSS".
The reason is in the javadoc for SimpleDateFormat:
Pattern letters are usually repeated, as their number determines the exact presentation:
...
Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.
Apparently, you can change this by calling setLenient(false). However, the javadocs don't specify what the actual effect of leniency is.
By contrast, the javadoc for DateTimeFormatter simply says "the count of pattern letters determines the format", making no distinction between formatting and parsing.
Why are they different? You would need to ask the people who designed the DateTimeFormatter API, but I imagine it was that the designers considered the ad hoc and unspecified nature of SimpleDateFormat (default) lenient parsing mode to be harmful.
How do you simply get DateTimeFormatter to accept dates with one or 3 digits millisecond values?
One approach would be to create the formatter using a DateTimeFormatterBuilder. This allows you to specify a minimum and maximum width for any field in the format.

Regex pattern for date format yyyy/MM/dd

I need to validate a date with format yyyy/MM/dd using a regex pattern. I already have a regex for the format dd/MM/yyyy.
(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)
I'm using the validation from this link http://www.mkyong.com/regular-expressions/how-to-validate-date-with-regular-expression. I need the validation for yyyy/MM/dd. Can anyone help me?
I have found the answer:
((?:19|20)\\d\\d)/(0?[1-9]|1[012])/([12][0-9]|3[01]|0?[1-9])
Old question, I know, but as I've just had cause to do this:
\d{4}\\\d{2}\\\d{2}
Looks a lot neater to my eyes than the other suggestions, and works outside of the 20th/21st century (unclear if OP required this or not).
However, my implementation will match for dates such as 9999/99/99 (clearly invalid) - but as a commenter suggested, SimpleDateFormat is the tool for that kind of validation, in my opinion.
If OP were able to use SimpleDateFormat as well as regex, then this would suffice:
public static final boolean isDateValid(String date) {
if (!date.matches("\d{4}\\\d{2}\\\d{2}"))
return false;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
sdf.parse(date);
return true;
} catch (ParseExceptione) {
return false;
}
}
NB. Usual caveats about SimpleDateFormat not being thread safe etc.
Here is my take on it:
((19|20)[0-9]{2})/((0?[1-9])|1[012])/((0?[1-9])|(1[0-9])|(3[01]))
i think this helpful for u...
var regdate = /^(19[0-9][0-9]|20[0-9][0-9])\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])$/;
A simple regex plus a SimpleDateFormat doesn't filter a String date like "2014\26\26", then it would not suffice.
So maybe the best approach is a fully strict regex pattern.
If you turn over your regex (Java) expression from the mkyong website you should be done. As you were already suggested:
String pattern = "((?:19|20)\\d\\d)/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])";
And for extra assurance you can add a SimpleDateFormat. Here is my extra verbose approach:
if(stringDate.length()==10 && stringDate.matches("((?:19|20)\\d\\d)/(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])")){
Date d=null;
String checkDate=null;
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
try {
//Also parses the String as a Date with the format "yyyy/MM/dd"
//to be sure that the passed string is correct
d=df.parse(stringDate);
} catch (ParseException e) {
e.printStackTrace();
}
if (d != null) {
//Transforms the Date into a String with the format "yyyy/MM/dd"
checkDate=df.format(d);
System.out.println(checkDate);
}
}
Here is an another simple approach, write a small method that converts the string input to date and convert back the date to string. Then compare both string are equal. If equal then date is correct else its incorrect. All validations are taken care by this approach.
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDate {
public static boolean isValidDateFormat(String value, String format) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
date = sdf.parse(value);
if (!value.equals(sdf.format(date))) {
date = null;
}
} catch (Exception ex) {
return false;
}
return date != null;
}
public static void main(String[] args) {
String format = "yyyy/MM/dd";
System.out.println("2017/02/31 isValidDateFormat: " + isValidDateFormat("2017/02/31", format));
System.out.println("2017/03/31 isValidDateFormat: " + isValidDateFormat("2017/03/31", format));
System.out.println("2017/04/31 isValidDateFormat: " + isValidDateFormat("2017/04/31", format));
System.out.println("2017/13/31 isValidDateFormat: " + isValidDateFormat("2017/04/31", format));
System.out.println("2017/01/35 isValidDateFormat: " + isValidDateFormat("2017/01/35", format));
System.out.println("017/01/30 isValidDateFormat: " + isValidDateFormat("017/01/30", format));
// output :
//2017/02/31 isValidDateFormat: false
// 2017/03/31 isValidDateFormat: true
// 2017/04/31 isValidDateFormat: false
// 2017/13/31 isValidDateFormat: false
// 2017/01/35 isValidDateFormat: false
// 017/01/30 isValidDateFormat: false
}
}
Just for fun, I wanted to see how the regex Jon Skeet's very valid comment mentioned (that a regex handling leap years correctly would be horrendous) would look like. And look - he was right ;)
^
(?:(?:19|2[01])\d\d\/(?:1[02]|0[13578])\/(?:[0-2]\d|3[01])) # 31 day months
|
(?:(?:19|2[01])\d\d\/(?:(?:11|0[469])\/(?:[0-2]\d|30))) # 30 day months
|
(?:(?:19|2[01])(?:[02468][1235679]|[13579][01345789])|1900|2100)\/02\/(?:[01]\d|2[0-8]) # Non leap year
|
(?:(?:(?:19|21)(?!00)|20)(?:[02468][048]|[13579][26]))\/02\/(?:[01]\d|2[0-9]) # Leap year
$
See it here at regex101.
It tests using four alternations:
31 day months
30 day months
February non-leap years
February leap years
Note that leap years are the years that are a multiple of four. An exception to that rule are multiples of 100 except if it's a multiple of 400. (Phew... This is what makes it horrendous.)
It's regexp date format(dd.MM.yyyy). You can adapt this one for you.
(((0[1-9]{1}|1[0-9]|2[0-9]).(0[1-9]|1[0-2]))|(30.(04|06|09|11))|((30|31).(01|03|05|07|08|10|12))).[0-9]{4}

Lenient SimpleDateFormat acting strange

I understand that, in order to properly validate date strings, one must make DateFormat instances non-lenient to get all ParseExceptions from malformed dates. But consider
String dubiousDate = "2014-04-01";
DateFormat sdf = new SimpleDateFormat( "yyyyMMdd");
Date d;
try {
d = sdf.parse( dubiousDate);
System.out.println( dubiousDate + " -> " + d);
} catch ( ParseException e) {
e.printStackTrace();
System.err.println( dubiousDate + " failed");
}
this will give
2014-04-01 -> Wed Dec 04 00:00:00 CET 2013
Now I can understand that the lenient calendars try to be nice and accept funny negative numbers, but this interpretation looks like the -01 is considered as month, even though it appears last, where the days are. And the -04 months become 04 days, with the minus ignored.
In all leniency, why would this make sense to anyone?
I see another possible interpretation:
In the pattern yyyyMMdd the month part is limited to exact two chars because there are no separators between the different numerical fields. So "-0" will be seen as month which is just zero and is one month behind January yielding December in previous year.
After having "parsed" the fake month, the day part comes with "4" stopping before the second minus char. The result is then the fourth of December.
Finally, the remaining chars "-01" are simply ignored. This is typical for the class SimpleDateFormat about how to handle non-digit trailing chars, for example see this code:
String dubiousDate = "2014-04-01xyz";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d;
try {
d = sdf.parse(dubiousDate);
System.out.println(dubiousDate + " -> " + d);
// output: Tue Apr 01 00:00:00 CEST 2014
} catch (ParseException e) {
e.printStackTrace();
System.err.println(dubiousDate + " failed");
}
As thumb rule, with only two equal symbol chars MM or dd the parser will only consume up to at most two chars (if digits are found).
Some research about Java 8:
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
builder.parseLenient();
builder.append(DateTimeFormatter.ofPattern("yyyyMMdd"));
DateTimeFormatter dtf = builder.toFormatter();
String dubiousDate = "2014-04-01";
LocalDate date = LocalDate.parse(dubiousDate, dtf);
System.out.println(date);
According to JDK-8-documentation the formatter constructed this way should behave leniently, but unfortunately still throws an exception:
"Exception in thread "main" java.time.format.DateTimeParseException: Text '2014-04-01' could not be parsed at index 3"
Best option would be in lenient case - theoretically - if the parser just ignores the minus chars. But obviously this is not possible with JSR-310 (still too strict). Well, SimpleDateFormat is lenient, but in rather a wrong way.
This doesn't make sense. It sounds like a bug to me.
I think the right answer is to wait for Java 8 where dates are finally done right. Your code, for example, could now change to something like what is below. And, Java will throw an exception, like it should.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String dubiousDate = "2014-04-01";
LocalDate d;
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
d = LocalDate.parse(dubiousDate, formatter);
System.out.println(dubiousDate + " -> " + d);
}
catch (Exception e) {
e.printStackTrace();
System.err.println(dubiousDate + " failed");
}
}
}
}

Categories