Wrong date is getting printed [duplicate] - java

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

Related

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

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.

I have created a method to add minutes to date time but does not as expected in Java [duplicate]

This question already has answers here:
Parsing a string to date format in java defaults date to 1 and month to January
(2 answers)
Is SimpleDateFormat in Java work incorrect or I did any mistake? See code sample [duplicate]
(2 answers)
Why is the month changed to 50 after I added 10 minutes?
(13 answers)
Closed 3 years ago.
This is a java code where it adds the date with time hours and minutes if a possible day to
timeAddition("06/20/2019;23:30", 60, "m")
public static String timeAddition(String TimeAndDate, int addTime, String units_M_H) {
try {
String returnTime = TimeAndDate;
final long ONE_MINUTE_IN_MILLIS = 60000;
DateFormat dateFormat = new SimpleDateFormat("MM/dd/YYYY;HH:mm");
Date date = dateFormat.parse(TimeAndDate);
Calendar Cal = Calendar.getInstance();
Cal.setTime(date);
if (units_M_H.trim().equalsIgnoreCase("h")) {
Cal.add(Calendar.HOUR_OF_DAY, addTime);
returnTime = dateFormat.format(Cal.getTime()).toString();
} else if (units_M_H.trim().equalsIgnoreCase("m")) {
long timeInMili = date.getTime();
date = new Date(timeInMili + (addTime * ONE_MINUTE_IN_MILLIS));
returnTime = dateFormat.format(date);
}
return returnTime;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
The expected output is 06/21/2019;00:30 but the actual output is 12/31/2019;00:30
java.time
Do not reinvent the wheel, Java already has all instruments to do such operations. See the java.time package of classes built into Java. See Tutorial.
String timestamp = "06/20/2019;23:30";
LocalDateTime ldt = LocalDateTime.parse(timestamp,
DateTimeFormatter.ofPattern("MM/dd/yyyy;HH:mm"));
System.out.println(ldt);
LocalDateTime ldt2 = ldt.plus(60L, ChronoUnit.MINUTES);
System.out.println(ldt2);
Will print that you expect.
2019-06-20T23:30
2019-06-21T00:30
Hope this helps!
Use yyyy for year.
YYYY represents week year.

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

How to validate a date in Java? [duplicate]

This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 7 years ago.
I have a date coming in this format -
2015-4-10T11:20:56
I need to validate the date and make sure date it is not greater than current date. Meaning if today is April 10th, then it should not be April 11th or greater than that.
String abc = "2015-4-10T11:20:56";
if(abc is greater than todays date) {
// log an error
}
How can I do this?
UPDATE:-
I tried parssing like this but it didn't worked -
String abc = "2015-4-10T11:20:56";
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
try {
format.parse(abc);
} catch (ParseException e) {
e.printStackTrace();
}
You have to convert the string to a date object.
You can use a SimpleDateFormat.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d'T'HH:mm:ss");
Date date = sdf.parse(dateStr);
if (date.compareTo(new Date()) > 0) {
// log an error
}
This should work for you:
String abc = "2015-4-10T11:20:56";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
Date mydate = df.parse(abc);
Calendar c = Calendar.getInstance();
c.setTime(mydate);
Calendar today = Calendar.getInstance();
if (c.compareTo(today)>=0){
}
You can try like this using compareTo
Date date = null;
String str = "2015-4-10T11:20:56";
try {
DateFormat f = new SimpleDateFormat("yyyy-M-d'T'HH:mm:ss");
f.setLenient(false);
date = f.parse(str);
if (date.compareTo(new Date()) > 0) {
// your code
}
} catch (ParseException e) {
e.printStackTrace();
}

Categories