Why is the expected exception not thrown on parsing invalid date? [duplicate] - java

This question already has answers here:
Calculate days between two Dates in Java 8
(14 answers)
SimpleDateFormat parse in wrong date for 29 February [duplicate]
(1 answer)
Closed 1 year ago.
I get two strings and I must transform them into dates and show the difference in days between them. But I must throw an exception if one of the two dates is invalid.
This is the code I have so far for this task:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String d1 = sc.next();
String d2 = sc.next();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
Date date1 = formatter.parse(d1);
Date date2 = formatter.parse(d2);
long dt = (date1.getTime() - date2.getTime()) + 3600000;
long days = (dt / 86400000L);
System.out.println(days);
} catch (ParseException e) {
System.out.println("Data inválida");
e.printStackTrace();
}
}
}
But if I enter an invalid date like 02/29/2021, it converts to 03/01/2021 instead of throwing the exception.

java.time
#MCEmperor how i can change my formatter to use LocalDate?
Like MCEmperor I recommend that you use java.time, the modern Java date and time API, for your date work.
public class Main {
private static final DateTimeFormatter FORMATTER
= DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ROOT)
.withResolverStyle(ResolverStyle.STRICT);
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String d1 = sc.next();
String d2 = sc.next();
try {
LocalDate date1 = LocalDate.parse(d1, FORMATTER);
LocalDate date2 = LocalDate.parse(d2, FORMATTER);
long days = ChronoUnit.DAYS.between(date2, date1);
System.out.println(days);
} catch (DateTimeParseException dtpe) {
System.out.println("Data inválida");
dtpe.printStackTrace();
}
}
}
Example session:
03/02/2021
02/29/2021
Data inválida
java.time.format.DateTimeParseException: Text '02/29/2021' could not be parsed: Invalid value for MonthOfYear (valid values 1 - 12): 29
at java.base/java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:2017)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1952)
at java.base/java.time.LocalDate.parse(LocalDate.java:428)
at Main.main(Main.java:18)
You may also notice in the code how much more natural and simple it is to calculate the number of days between the two dates.
What went wrong in your code?
But if I enter an invalid date like 02/29/2021, it converts to
03/01/2021 instead of throwing the exception.
That’s as designed. And I agree with you, it’s a confusing, surprising and unfortunate design. When you pass February 29 in a non-leap year to a SimpleDateFormat with default settings, it just takes it as the day after February 28, that is, March 1. It’s just one of very many reasons not to use that class.
Link
Oracle tutorial: Date Time explaining how to use java.time.

Related

I want to Add Months In date like 6/5/2021 to 6/6/2021, but there is only increment in Days but not in Month and Year [duplicate]

This question already has answers here:
SimpleDateFormat ignoring month when parsing
(4 answers)
Closed 1 year ago.
I want to add 2 Months in another Date but he only add 60 Days in Date and there is no increment in Months of the Date as well as in Year.
I'm using following code for adding Date in another Date. Days adding correctly but there is no increment in Month of Date. if I add 60 Days then he add but again there is no increment in Month as well as in Year. If someone help me to resolve problem then I really thank full!!!
String dob = "06/05/2021";
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
Calendar c = Calendar.getInstance();
try {
c.setTime(sdf.parse(dob));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, 60);
c.add(Calendar.MONTH,2); // Not Working
sdf = new SimpleDateFormat("dd/mm/yyyy");
Date resultdate = new Date(c.getTimeInMillis());
String incToDate = sdf.format(resultdate);
Toast.makeText(this, incToDate, Toast.LENGTH_SHORT).show();
Your pattern is not correct, it basically reads two digits for day of month/two digits for minute of hour/4 digits for year. I'm guessing you did not want any minutes of hour in this pattern, so change the lower-case ones to upper-case ones.
If you can use java.time, you could get the desired result like this:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
// provide an example date as String
String dob = "06/05/2021";
// create a formatter that can parse a String in the given format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// parse the String to a LocalDate using the previously defined formatter
LocalDate localDob = LocalDate.parse(dob, dtf);
// print the (formatted) result just to see if parsing has worked
System.out.println("Just parsed " + localDob.format(dtf));
// add two months and print a result phrase
LocalDate localDobTwoMonthsLater = localDob.plusMonths(2);
System.out.println("Adding two months results in "
+ localDobTwoMonthsLater.format(dtf));
// for completeness, add 60 days and print the result
LocalDate localDobSixtyDaysLater = localDob.plusDays(60);
System.out.println("Adding sixty days results in "
+ localDobSixtyDaysLater.format(dtf));
}
}
This code prints
Just parsed 06/05/2021
Adding two months results in 06/07/2021
Adding sixty days results in 05/07/2021

Wrong date is getting printed [duplicate]

This question already has answers here:
Java date format conversion - getting wrong month
(8 answers)
Getting wrong month when using SimpleDateFormat.parse
(3 answers)
Closed 5 years ago.
I am trying to simply pass a date and parse it using simpledateformat. But instead of printing the correct value, it's printing wrong date.
public static void main(String[] args) {
getAge("29-02-2016");
}
public static void getAge(String dob1) {
DateFormat format = new SimpleDateFormat("dd-mm-yyyy");
try {
Date dob = format.parse(dob1);
System.out.println(dob);
Calendar realDob = Calendar.getInstance();
realDob.setTime(dob);
System.out.println(realDob.get(Calendar.YEAR));
Calendar today = Calendar.getInstance();
int age = today.get(Calendar.YEAR) - realDob.get(Calendar.YEAR);
if(age >=18) {
System.out.println("18 years");
} else {
System.out.println("Underage");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
its printing : Fri Jan 29 00:02:00 IST 2016 but it should be February
mm is for minutes, use MM: DateFormat format = new SimpleDateFormat("dd-MM-yyyy");

How to get year, month, day from a String format in Java [duplicate]

This question already has answers here:
Illegal pattern character 'T' when parsing a date string to java.util.Date
(4 answers)
Closed 6 years ago.
I am working on a piece of work where I need to get year, month, day from a String in Java. The string is like that: 20170119T163048
Where 2017 is year, 01 is month, 19 is day, 16:30:48 is time.
I implemented code like this below:
public void convertStringToDate (String string) {
String dateInString = "";
SimpleDateFormat formatter = new SimpleDateFormat();
Date date = formatter.parse("20170119T163048");
System.out.println(date);
}
But seems like it does not work. Looking around and I actually found quite lots of similar answer but none of them really work for me so...
You Shall always refer to the documentation.Simple Date Format Documentation
public static void main(String[] args) throws Exception{
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
Date date = formatter.parse("20170119T163048");
System.out.println(date.toString());
}

Get the current week in Java [duplicate]

This question already has answers here:
Why do I get the "Unhandled exception type IOException"?
(6 answers)
java get week of year for given a date
(4 answers)
Closed 7 years ago.
I want to get the current week with a given date, e.g if the date is 2016/01/19, the result will be : week number: 3
I've seen some questions and answers about this but I'm not able to achieve what I want. Here is what I've done :
public static int getCurrentWeek() {
String input = "20160115";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
return week;
}
I've took this code from this question but I have an error on this line :
Date date = df.parse(input);
unhandled exception type ParseException
Use Java 8 LocalDate and WeekFields:
private int getCurrentWeek() {
LocalDate date = LocalDate.now();
WeekFields weekFields = WeekFields.of(Locale.getDefault());
return date.get(weekFields.weekOfWeekBasedYear());
}
Look at this changed code:
String input = "20160115";
String format = "yyyyMMdd";
try {
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println("Input " + input + " is in week " + week);
return week;
} catch (ParseException e) {
System.out.println("Could not find a week in " + input);
return 0;
}
You need to catch ParseException and deal with it somehow. This could mean returning a "default" number (0 in this case) or passing the exception along (by declaring a throws on your method)

Java date parsing issue - SimpleDateFormat automatically decrements month [duplicate]

This question already has answers here:
get the right Month format date java
(2 answers)
Closed 7 years ago.
I try to parse Date from String with pattern:
final static String DATE_RU_PATTERN = "dd.MM.yyyy";
private static SimpleDateFormat ruFormatter = new SimpleDateFormat(DATE_RU_PATTERN);
public static Date GetDateFromStringRuFormat (String dateString){
try {
return ruFormatter.parse(dateString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Why ruFormatter.parse(dateString) gives Date with decremented values of Month?
#Test
public void TestGetDateFromStringRuFormat(){
final String dateString = "24.09.2015";
Calendar actualCalendar = Calendar.getInstance();
Date actualResult = DateFormatHelper.GetDateFromStringRuFormat(dateString);
actualCalendar.setTime(actualResult);
assertEquals(9, actualCalendar.get(Calendar.MONTH)); // FAILS
assertEquals(24, actualCalendar.get(Calendar.DAY_OF_MONTH));
assertEquals(2015, actualCalendar.get(Calendar.YEAR));
}
Calendar like java.util.Date starts counting months from 0.
So whenever you want to do something meaningful with the month value, add 1 to it.
From the Javadoc:
Field number for get and set indicating the month. This is a
calendar-specific value. The first month of the year in the Gregorian
and Julian calendars is JANUARY which is 0; the last depends on the
number of months in a year.
Therfore your unit test should read:
assertEquals(9, actualCalendar.get(Calendar.MONTH) + 1);
Months in the Calendar class start at zero:
JANUARY = 0
FEBRUARY = 1
...
So September = 8 (http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#MONTH).
Try changing your test to:
assertEquals(Calendar.SEPTEMBER, actualCalendar.get(Calendar.MONTH));

Categories