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