Why does DateTimeException only happens for the month of january [duplicate] - java

This question already has answers here:
SimpleDateFormat. format returning wrong date
(2 answers)
Convert java.util.Date to java.time.LocalDate
(14 answers)
Closed 9 months ago.
what does this error mean?
Exception in thread "AWT-EventQueue-0" java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 0
It only happens for the month of January
this is my line of code
public int computeAge(Date birthDay) throws ParseException {
LocalDate birthdate = LocalDate.of(birthDay.getYear(), birthDay.getMonth(), birthDay.getDay());
LocalDate curDate = LocalDate.now();
Period p = Period.between(birthdate, curDate);
return p.getYears();
}

This happens because Date uses month numbers from 0 to 11, but LocalDate uses month numbers from 1 to 12. So even if your program doesn't throw the DateTimeException, it won't give you the correct result.
Please stop using the Date class, and just use classes from the java.time package instead. Those particular methods - getDay(), getMonth() and getYear() were deprecated last century, if I recall correctly.
In this case, you should use LocalDate instead of Date, because it expresses a combination of year, month and day, with no time component.

Related

Verifying if date from String is the last day of the month [duplicate]

This question already has answers here:
Is it the last day of the month?
(4 answers)
Closed 11 months ago.
My input string date is as below:
String date = "1/31/2022";
I am transforming to a date:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
How do I know if my date is the last day of the month?
E.g.: for a String "1/31/2022" the output should be true. For 2/2/2023 it should be fast.
This is to run in Groovy in Jenkins but I believe I could use java as well
SimpleDateFormat is obsolete. I'd use the modern stuff from the java.time package.
Use single character M and d if not padding single-digit values with a leading zero.
DateTimeFormatter MY_FORMAT = DateTimeFormatter.ofPattern("M/d/uuuu");
LocalDate x = LocalDate.parse("1/31/2022", MY_FORMAT);
if (x.getDayOfMonth() == x.lengthOfMonth()) {
// it is the last day of the month
}

Converting an integer to expected Date value in java [duplicate]

This question already has answers here:
Convert day of the year to a date in java
(2 answers)
Closed 3 years ago.
In the below Java class, I need to write the logic of converting an int to Date as explained below. And this program is not related to adding number of days to current date.
If endDay value is 1, then date should print as Jan 1st 2020.
If endDay value is 28, then date should print as Jan 28th 2020.
If endDay value is 35, then date should print as Feb 4th 2020.
If endDay value is 60, then date should print as Feb 29th 2020.
If endDay value is 70, then date should print as March 10th 2020.
Note: value of endDay (1) always starts from January 1st of every year.
import java.util.Date;
public class TestDate
{
public void startEndDate(int endDay)
{
Date date=new Date();
//logic to print the date here
System.out.println("For the given end day of "+endDay+" the date returned is : "+date);
}
public static void main(String[] args)
{
startEndDate(35);
startEndDate(49);
startEndDate(70);
}
}
Can any one suggest me the ideas on how to write the logic for above one ?
java.time and Year.atDay()
public static void startEndDate(int endDay)
{
LocalDate date = Year.of(2020).atDay(endDay);
System.out.println("For the given end day of " + endDay
+ " the date returned is : " + date);
}
Let’s try it out:
startEndDate(35);
startEndDate(49);
startEndDate(70);
Output is:
For the given end day of 35 the date returned is : 2020-02-04
For the given end day of 49 the date returned is : 2020-02-18
For the given end day of 70 the date returned is : 2020-03-10
The documentation of Year.atDay() explains:
Combines this year with a day-of-year to create a LocalDate.
Please fill in your desired year where I put 2020.
I recommend you don’t use Date. That class is poorly designed and long outdated. Instead I am using Year and LocalDate, both from java.time, the modern Java date and time API.
A comment suggested regarding your question as a question of adding a number of days to December 31 of the previous year. IMO regarding it as finding a date from the number of the day-of-year gives a somewhat more elegant solution.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Documentation of Year.atDay(int dayOfYear)
Documentation of LocalDate.ofYearDay(), a good alternative

Why there is a difference between GregorianCalendar.getTimeInMillis() and GregorianCalendargetTimeInMillis(1970.01.01)) [duplicate]

This question already has answers here:
How do I calculate someone's age in Java?
(28 answers)
Why is January month 0 in Java Calendar?
(18 answers)
Closed 3 years ago.
I have tried to compare to Dates the Birthdate and the Current date
and then I tried to get the age.
But the Current date Funtion begins with another Date than the given date
My Code:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
long ms = System.currentTimeMillis() - birthdate.getTimeInMillis();
double years = (((double)ms / 1000)/31536000) ;
System.out.print(years);
// years Shoud be 18 here but it returns 17.3
if (years > 18) {
// Code Block
}
else{
System.out.print("to Jung");
}
Check the Constructor on GregorianCalendar.
public GregorianCalendar(int year,
int month,
int dayOfMonth)
Constructs a GregorianCalendar with the given date set in the default time zone with the default locale.
year - the value used to set the YEAR calendar field in the calendar.
month - the value used to set the MONTH calendar field in the calendar. Month value is 0-based. e.g., 0 for January.
dayOfMonth - the value used to set the DAY_OF_MONTH calendar field in the calendar.
You are creating a July 20th date, which is coincidentally offset by a single month, or approximately 0.08 years.
LocalDate birthdate = LocalDate.of(2001,06,20);
LocalDate currentdate = LocalDate.now();
int years = Period.between(birthdate , currentdate).getYears();
if (years >= 18) {
// Code
} else {
System.out.print("Sie sind zu Jung");
}
It Worked like this but I must change the hole code because everything was written with the GeorgianCalender.
I couldn't tell you why exactly your code, which should technically work, doesn't: there seems to be inaccuracies (leap days?) in the Calendar, or I'm missing something. Thanks to Compass, I know that I was missing something: months are 0-indexed in the constructor for Gregorian Calendar. 06 is July.
However, you shouldn't compare dates like this. If you don't want to use any other library, you can do this:
GregorianCalendar birthdate = new GregorianCalendar(2001,06,20);
GregorianCalendar today = new GregorianCalendar();
birthdate.add(Calendar.YEAR, 18);
System.out.print(birthdate.getTime().after(today.getTime()));

Subtracting 5 minutes from epoch date [duplicate]

This question already has answers here:
subtracting two days from current date in epoch milliseconds java [duplicate]
(5 answers)
Closed 8 years ago.
What is the best way to subtract 5 minutes from a given epoch date ?
public long fiveMinutesAgo(String epochDate) {
//ToDo
return fiveMinBack;
}
epochDate has to be a Date. Use a Calendar:
Calendar calendar = Calendar.getInstance();
calendar.setTime(epochDate);
calendar.add(Calendar.MINUTE, -5);
Date result = calendar.getTime();
You can use any of the above mentioned methods by other user , but if interested give a try to
Java 8 Date and Time API
public void subtract_minutes_from_date_in_java8 ()
{
LocalDateTime newYearsDay = LocalDateTime.of(2015, Month.JANUARY, 1, 0, 0);
LocalDateTime newYearsEve = newYearsDay.minusMinutes(1);// In your case use 5 here
java.time.format.DateTimeFormatter formatter =java.time.format.DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss S");
logger.info(newYearsDay.format(formatter));
logger.info(newYearsEve.format(formatter));
}
Output :
01/01/2015 00:00:00 CST
12/31/2014 23:59:00 CST
Class LocalDateTime is an immutable date-time object present in java.time package in Java 8 that represents a date-time, often viewed as year-month-day-hour-minute-second.
Below is the syntax of of() method used :
static LocalDateTime of(int year, int month, int dayOfMonth, int hour, int minute)
which obtains an instance of LocalDateTime from year, month, day, hour and minute, setting the second and nanosecond to zero.
You can subtract 5 minute equivalent of miiliseconds from date you get:-
//convert input string epochDate to Date object based on the format
long ms=date.getTime();
Date updatedDate=new Date(ms - (5 * 60000)); //60000 is 1 minute equivalent in milliseconds
return updatedDate.getTime();
Here's a body for your method:
private static final long FIVE_MINS_IN_MILLIS = 5 * 60 * 1000;
public long fiveMinutesAgo(String epochDate) throws ParseException {
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
long time = df.parse(epochDate).getTime();
return time - FIVE_MINS_IN_MILLIS;
}
The time is in millis-since-the-epoch, so to find out five minutes before you simply have to subtract 5 mins in milliseconds (5 * 60 * 1000).
I would suggest renaming the method to: fiveMinutesBefore() and perhaps breaking it into two methods: one for parsing string dates into times and the other for subtracting minutes from the time.
You might also consider using Joda-Time as it's much better designed (and thread-safer) than the standard Java date package.

Getting hours,minutes, and seconds from Date? [duplicate]

This question already has answers here:
Java: getMinutes and getHours
(13 answers)
Closed 8 years ago.
I want to get the current hour,minute, and second from the Date object.
This is my code:
Date date = new Date();
int hour = date.getHours();
But I get a kind of error, the getHours() part doesnt work. I get a "The method getHours() from the type Data is deprecated". What does that mean, and how do I get the hour,minutes, and seconds?
Use Calendar:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hours = cal.get(Calendar.HOUR_OF_DAY);
From Date javadoc:
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.MINUTE).
Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone. The value returned is between 0 and 59.

Categories

Resources