Calculating the age of two LocalDates - java

Code:
public String Calcage(){
int age = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date birth = sdf.parse(dateOfBirth);
Date d = new Date();
LocalDate birthday = birth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate now = d.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
age = Period.between(birthday, now).getYears();
} catch (ParseException e) {
e.printStackTrace();
}
return String.valueOf(age);
}
PROBLEM: It returns zero every time. The Date which I use for testing is 1985-01-07

If you are actually using 1985-01-07 it correctly returns 0 and should also throw a ParseException which will be caught from the catch block and the stacktrace will be printed.
Your code should work for 07.01.1985 and return 35.
if you want nevertheless to use 1985-01-07 you should edit the specified format to "yyyy-dd-MM" or "yyyy-MM-dd"

Related

Date Formatting using SimpleDateFormat

Here the user need to enter the Name, Date of Birth and Date of joining. The program need to check whether the entered date is valid with any of the given 3 formats dd/MM/yyyy , dd-MMM-yyyy and dd MMMM yyyy. If invalid, user need to re-enter. Finally i want to print back an auto-increment ID,Name,Date of Birth and Date of Joining back. Can you help me with the program. I cannot find any solution for exception handling.
public class EmployeeInfo {
int id;
static String name, DoBS, DoJS;
Date DoB, DoJ;
public void checkDate(String dt) throws ParseException {
SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
SimpleDateFormat sdf3 = new SimpleDateFormat("dd MMMM yyyy");
Date date = null;
if (date == sdf1.parse(dt))
try {
date = sdf1.parse(dt);
}
catch (ParseException e) {
e.printStackTrace();
DoB=date;
}
else if (date == sdf2.parse(dt))
try {
System.out.println("hsd");
date = sdf2.parse(dt);
}
catch (ParseException e) {
e.printStackTrace();
}
else if(date==sdf3.parse(dt))
{
try{
date=sdf3.parse(dt);
}
catch(ParseException e){
e.printStackTrace();
}
}
{
void print() {
System.out.println("User ID: " + id);
System.out.println("Name: " + name);
System.out.println("Date Of Birth: " + DoB);
System.out.println("Date of Joining: " + DoJ);
}
public static void main(String[] args) throws ParseException {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the name: ");
name = scanner.nextLine();
System.out.println("Enter the Date Of Birth: ");
DoBS = scanner.nextLine();
System.out.println("Enter the Date of Joining: ");
DoJS = scanner.nextLine();
EmployeeInfo e = new EmployeeInfo();
e.checkDate(DoBS);
e.print();
}
}
As for the actual checking of dates, if you only want to support those three date formats you could simply use three nested try catch statements. Something like this:
try {
date = sdf1.parse(dt);
} catch (ParseException e) {
try {
date = sdf2.parse(dt);
} catch (ParseException e1) {
try {
date = sdf3.parse(dt);
} catch (ParseException e2) {
// TODO: Whatever to do when it doesn't find a date
}
}
}
If you want a more dynamic approach you could put the SimpleDateFormat objects in an array and use a loop with a try-catch inside.
EDIT:
Alright, what you want to do is make the checkDate method return a Date object. If it can't parse a date in your three formats, either return null or throw an exception. When entering the dates, you want to have a while loop checking whether or not the date is valid, using the checkDate method, and make the user reenter if it's invalid.
A few notes about your code:
In Java, fields of classes are usually private, with getter and setter methods to control them - this is called encapsulation.
Static fields are meant for variables that are the same across all of your instances. Name and dates specific to one EmployeeInfo object should not be static. You should create an EmployeeInfo object and then set the respective values of the object.
It is also common practice to have all your methods be either private or public (or protected in the case of inheritance) depending on their intended usage.
I suggest you read up a little on the basics of OOP in Java.
You asked several things in your question but regarding the date-paersing issue, you could implement it like following :
private static final List<DateFormat> ORDERED_FORMATS = Arrays.asList(new SimpleDateFormat("dd/MM/yyyy"),new SimpleDateFormat("dd-MMM-yyyy"),new SimpleDateFormat("dd MMM yyyy"));
public static Date parseDate(String date) {
for(DateFormat format : ORDERED_FORMATS){
Date result = tryParse(date, format);
if(result != null){
return result;
}
}
throw new IllegalArgumentException("Could not parse "+date);
}
private static Date tryParse(String date, DateFormat format){
try{
return format.parse(date);
} catch (ParseException e) {
System.out.println("Too bad : "+e.getMessage());
}
return null;
}

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

Having trouble adding times to generate time list

I'm trying to generate a time list in Java. I've read this as to how to add two times together. I wrote the code using floats before converting to using times so I know that the general format of the code works. This is the code that I'm having difficulty with:
public class Test2 {
public static void main(String[] args){
String time = "09:00";
String quarterHour = "00:15";
String halfHour = "00:30";
String quarterHour3 = "00:45";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
Date times;
Date temp;
long sum;
try {
times = timeFormat.parse(time);
while(times.before(timeFormat.parse("15:15"))){
System.out.println("Timelist: " + time);
if((times.equals(timeFormat.parse("10:15"))) || (times.equals(timeFormat.parse("13:45")))){
temp = timeFormat.parse(halfHour);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
else if(times.equals(timeFormat.parse("11:45"))){
temp = timeFormat.parse(quarterHour3);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
else{
temp = timeFormat.parse(quarterHour);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The result I get from that is simply 09:00. It goes through the loop once and ends.
I followed it through the debugger and what's happening is that when it adds the quarterHour to times it adds 12:15 and not the 00:15 as it's supposed to.
This seems to have something to do with me using 24 hour time as when I change the:
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
to:
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
It works - except that it goes into an eternal loop.
Question: How do I get it to add only 15 minutes to the time while using 24 hour format?
Use a Calendar, or if you're using Java 8 you might use the new java.time classes like
String timeStr = "09:00";
DateFormat timeFormat = new SimpleDateFormat("HH:mm");
try {
LocalDateTime endTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(timeFormat.parse("15:15").getTime()),
ZoneOffset.ofHours(0));
Instant instant = Instant.ofEpochMilli(timeFormat.parse(timeStr)
.getTime());
LocalDateTime time = LocalDateTime.ofInstant(instant,
ZoneOffset.ofHours(0));
while (time.isBefore(endTime)) {
time = time.plus(15, ChronoUnit.MINUTES);
Instant output = time.atZone(ZoneOffset.ofHours(0)).toInstant();
System.out.println(timeFormat.format(Date.from(output)));
}
} catch (Exception e) {
e.printStackTrace();
}
or, with the Calendar like
String timeStr = "09:00";
DateFormat timeFormat = new SimpleDateFormat("HH:mm");
try {
Calendar cal = Calendar.getInstance();
cal.setTime(timeFormat.parse(timeStr));
Date when = timeFormat.parse("15:15");
while (cal.getTime().before(when)) {
cal.add(Calendar.MINUTE, 15);
System.out.println(timeFormat.format(cal.getTime()));
}
} catch (Exception e) {
e.printStackTrace();
}
Add this line to your code:
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
immediately after you declare timeFormat.
It fixes your problem on my computer.

parsing only the Year in a DateFormat Java

I get a returned parsed JSON result with string values in the form of dates like "27-11-2012" which i parse to a date Object. my code for this is:
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
//if(s.matches(""))
format = new SimpleDateFormat("dd-MMM-yyyy");
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
now my issue is, a feature has been implemented that sometimes the json only returns a year object like "2012" and is giving me an "ParseException: Unparseable date" as expected. I was thinking of using regex to match the string pattern and parse from there, but not sure how to do that. Any ideas and also anyway to parse only year in a DateFormat?
I'd try:
public Date stringToDateReport(String s){
DateFormat format;
Date date = null;
format = new SimpleDateFormat("dd-MM-yyyy");
if(s.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
//you should do a real logging here
e.printStackTrace();
}
return date;
}
The logic behind is to check if the string is only 4 long, then apply the different format. In this case, this easy method is sufficient, but in other methods, the use of regexes might be required.
Try this code
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
if(s.indexOf("-") < 0){
format = new SimpleDateFormat("yyyy");
}else{
format = new SimpleDateFormat("dd-MMM-yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Is there the possibility in have another format in the String s ? Or just these two?
public Date stringToDateReport(String strDate){
DateFormat formatnew SimpleDateFormat("dd-MM-yyyy");
Date date = null;
if(strDate.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(strDate);
} catch (ParseException e) {
//error parsing date
e.printStackTrace();
}
return date;
}
then call it like this :
String strDate = yourJson.getString("date");
Date d = stringToDateReport(strDate);

SimpleDateFormat and Date Comparison not given correct ouput

try {
Date sysDate = new SimpleDateFormat("dd/mm/yyyy").parse(_sysDate);
Date userDate = new SimpleDateFormat("dd/mm/yyyy").parse(_userDate);
if (userDate.compareTo(sysDate) > 0)
return false;
else
return true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above is my following code snippet to check two dates which is greater or not.
When I am giving :
sysdate=12/9/2012 and userdate=11/9/2012 or 10/8/2012 or 15/9/2011 it is giving the correct output
But when I am giving :
sysdate=12/9/2012 and userdate=13/8/2012 or 15/7/2012 or 16/6/2012 it is giving incorrect output.
To my analysis I have come to this point if I choose any month between Jan' 12 to Aug '12 and select the day_of_month(i.e. 0,1,2,...,31) more than the current day_of_month (in this case 12), I always get an incorrect output.
Please suggest any possible solution.
The problem is the pattern which should be "dd/MM/yyyy" (with capital "MM" for month) instead of "dd/mm/yyyy" (with small "mm" which means minutes).
So, it should be as follows -
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date sysDate = df.parse(_sysDate);
Date userDate = df.parse(_userDate);
//...
try {
Date sysDate = new SimpleDateFormat("dd/MM/yyyy").parse(_sysDate);
Date userDate = new SimpleDateFormat("dd/MM/yyyy").parse(_userDate);
if (userDate.compareTo(sysDate) > 0)
return false;
else
return true;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Date pattern is wrong dd/MM/yyyy instead of dd/mm/yyyy.
see this data format change like this dd/MM/yyyy in place of dd/mm/yyyy.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html

Categories