I am using Selenium Webdriver for automation and need to retrieve the current age of a person to compare it with the age populated in the application.
My Code goes like :
String DOB = driver.findElement(By.id("")).getAttribute("value");
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date convertedDate = dateFormat.parse(DOB);
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date currentNow = currentDate.getTime();
System.out.println("Sys date: " + currentNow);
System.out.println("DOB Date: " + convertedDate);
Output:
Sys date: Tue Mar 05 12:25:19 IST 2013
DOB Date: Wed Mar 15 00:00:00 IST 1967
How can I retrieve the proper age so that I can compare it with application's age being auto-populated. Currently when we subtract by using .getYear() it is assuming the date of the year starting from Jan 1, hence not calculating the proper age.
Please help me on this so that I can successfully calculate the correct age.
If you're already comparing years, why not compare the Month/Day to the current one? The Calendar can do this for you with a little bit of coaxing.
//Retrieve date from application
String DOB = driver.findElement(By.id("")).getAttribute("value");
//Define the date format & create a Calendar for this date
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
Calendar birthday = Calendar.getInstance();
birthday.setTime(sdf.parse(DOB));
//Create a Calendar object with the current date
Calendar now = Calendar.getInstance();
//Subtract the years to get a general age.
int diffYears = now.get(Calendar.YEAR) - birthday.get(Calendar.YEAR);
//Set the birthday for this year & compare
birthday.set(Calendar.YEAR, now.get(Calendar.YEAR));
if (birthday.after(now)){
//If birthday hasn't passed yet this year, subtract a year
diffYears--;
}
Hope this helps.
Please check whether this helps you.
This method will give exact years in numbers.
public static int getDiffYears(Date first, Date last) {
Calendar a = getCalendar(first);
Calendar b = getCalendar(last);
int diff = b.get(YEAR) - a.get(YEAR);
if (a.get(MONTH) > b.get(MONTH) ||
(a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
diff--;
}
return diff;
}
Related
I need to convert Monthname + Year to a valid date range. It needs to work with leap years etc.
Examples
getDateRange("Feb",2015)
should find the range 2015-02-01 -- 2015-02-28
While
getDateRange("Feb",2016)
should find the range 2016-02-01 -- 2016-02-29
In Java 8, you can do that using TemporalAdjusters,
LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());
If you have only year and month, it is better to use YearMonth. From YearMonth you can easily get length of that month.
YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
int monthLen= ym.lengthOfMonth();
Java 8 made Date-Time operations very simple.
For Java 7 and below you could get away with something like this;
void getDate(String month, int year) throws ParseException {
Date start = null, end = null;
//init month and year
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
Date parse = sdf.parse(month);
Calendar instance = Calendar.getInstance();
instance.setTime(parse);
instance.set(Calendar.YEAR, year);
//start is default first day of month
start = instance.getTime();
//calculate end
instance.add(Calendar.MONTH, 1);
instance.add(Calendar.DAY_OF_MONTH, -1);
end = instance.getTime();
System.out.println(start + " " + end);
}
The output would be for "Feb", 2015:
Sun Feb 01 00:00:00 EET 2015
Sat Feb 28 00:00:00 EET 2015
Java 7 solution with default Java tools:
public static void getDateRange(String shortMonth, int year) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
// the parsed date will be the first day of the given month and year
Date startDate = format.parse(shortMonth + " " + year);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// set calendar to the last day of this given month
calendar.set( Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
// and get a Date object
Date endDate = calendar.getTime();
// do whatever you need to do with your dates, return them in a Pair or print out
System.out.println(startDate);
System.out.println(endDate);
}
Try (untested):
public List<LocalDate> getDateRange(YearMonth yearMonth){
List<LocalDate> dateRange = new ArrayList<>();
IntStream.of(yearMonth.lengthOfMonth()).foreach(day -> dateRange.add(yearMonth.at(day));
return dateRange
}
Java 8 provides new date API as Masud mentioned.
However if you are not working under a Java 8 environment, then lamma date is a good option.
// assuming you know the year and month already. Because every month starts from 1, there should be any problem to create
Date fromDt = new Date(2014, 2, 1);
// build a list containing each date from 2014-02-01 to 2014-02-28
List<Date> dates = Dates.from(fromDt).to(fromDt.lastDayOfMonth()).build();
How to convert Large Integer 130552992000000000 into date format?
This is today’s date and timestamp.
I tried with
Date d = new Date(130552992000000000L * 1000);
System.out.println("Date : " +d);
But its showing Date : Wed Dec 29 00:28:58 IST 45183249 date which is incorrect and not showing year too.
Thanks in advance.
You can use the Calendar#setTimeInMillis(long timemillis) method and the retrieve the Date by invoking the Calendar#getTime() method.
Long l = //some value
Calendar c = Calendar.getInstance();
c.setTimeInMillis(l);
Date date = c.getTime();
How do I find out the last month and its year in Java?
e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012.
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
java.time
Using java.time framework built into Java 8:
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24
earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
you can use the Calendar class to do so:
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01
The simplest & least error prone approach is... Use Calendar's roll() method. Like this:
c.roll(Calendar.MONTH, false);
the roll method takes a boolean, which basically means roll the month up(true) or down(false)?
YearMonth class
You can use the java.time.YearMonth class, and its minusMonths method.
YearMonth lastMonth = YearMonth.now().minusMonths(1);
Calling toString gives you output in standard ISO 8601 format: yyyy-mm
You can access the parts, the year and the month. You may choose to use the Month enum object, or a mere int value 1-12 for the month.
int year = lastMonth.getYear() ;
int month = lastMonth.getMonthValue() ;
Month monthEnum = lastMonth.getMonth() ;
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
You get by using the LocalDate class.
For Example:
To get last month date:
LocalDate.now().minusMonths(1);
To get starting date of last month
LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
Similarly for Year:
To get last year date:
LocalDate.now().minusYears(1);
To get starting date of last year :
LocalDate.now().minusYears(1).with(TemporalAdjusters.lastDayOfYear());
Here's the code snippet.I think it works.
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleMonth=new SimpleDateFormat("MMMM YYYY");
cal.add(Calendar.MONTH, -1);
System.out.println(simpleMonth.format(prevcal.getTime()));
I have a string (Jan12) (generated by applying some operations on current date {20-jan-2012}) Now i want to convert back this string into Date format . Also the value should be same i.e the new Date object should have value jan12 and not (20-jan-2012) . Pls help . I have tried doing
java.sql.Date.valueOf("Jan12") [this throws IllegalArgumentException]
and also
new SimpleDateFormat("MMMyy").parse("Jan12") [By this Date gets converted to 20-jan-2012]
Output required : A Date Object having value Jan12 (12 is the year)
My Code : new java.text.SimpleDateFormat("MMMyy").format(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(s)) // It is a string which gives Jan12
Now i really want to convert Mycode into a Date object
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s1 = df.format(now);
System.out.println(s1); // 2012-01-20
java.sql.Date d111=java.sql.Date.valueOf(s1);
System.out.println(d111); // 2012-01-20
DateFormat df1 = new SimpleDateFormat("MMMyy");
String s2 = df1.format(d111);
System.out.println(s2); //Jan12
Now i want s2 to be converted in Date object
#Aditya,
If you use the Str2 which gives "Jan12", there is no date part in that string and therefore if you convert it to a date object, it will get "Jan" as month, 12 as year but it cant find "day" in that String.
if you use below code
try
{
Date d2 = df1.parse(s2); //here s2 is your string which gives "JAN12"
System.out.println(d2);
}
catch(ParseException pe)
{
System.out.println("parse exception..");
}
The output to the above code will be:
Sun Jan 01 00:00:00 IST 2012
notice here that day part is reset to the first day of the month
Therefore, it is not possible to get a complete date object as your original Date, the month and year are preserved, but the day part is lost.
What do you mean "gets converted"? How your Date is displayed is a separate issue. Look into formatting a Date.
So the 12 is day, not a year - you should parse it as such. Aslo, you'll need to tell it what year this is:
System.out.println(new SimpleDateFormat("yyyyMMMdd").parse("2012" + "Jan12"));
Output
Thu Jan 12 00:00:00 EST 2012
Use the SimpleDateFormat class properly, it will do exactly what you want
String str_date="12-Jan-2012";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse(str_date);
Note: the formatter.parse() method throws ParseException, catch it;
If 12 is a year
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMyy").parse("Jan12"));
calendar.set(Calendar.DATE, 1);
Date date = calendar.getTime(); // First Jan 2012
If 12 is a day
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMdd").parse("Jan12"));
calendar.set(Calendar.YEAR, 2012);
Date date = calendar.getTime(); // 12 Jan 2012
I understand that you want to format your Date object into a String representation.
You can use SimpleDateFormat for this, analog to your second example:
Date d = new Date(112, 0, 20); //don't construct a date like this in production code, use a Calendar instance instead
String formattedDate = new SimpleDateFormat("MMMyy").format(d); // -> "Jan12"
Note that your Date object represents a specific point in time, it will always have a day and a time associated with it.
If you want to compare Dates with the resolution of a month, you have to set day and time to neutral values:
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
d = cal.getTime();
Just extend Date and customize it to use your favourite parse & format methods.
I'm trying to compare two dates with the current date. It seems not to work when I try to know if a date is the same as the current date. Here's what I do in my code :
//BeginDate is set earlier
Date myDate= new SimpleDateFormat("dd/MM/yyyy").parse(BeginDate);
Date now = new Date();
System.out.println("Now : " + now);
System.out.println("myDate : " + myDate);
System.out.println("equals : " + myDate.equals(now));
System.out.println(myDate.compareTo(now));
And I get this in the console :
Now : Thu Dec 29 00:28:45 CET 2011
myDate : Thu Dec 29 00:00:00 CET 2011
equals : false
-1
The first comparison should return true and the second "0" right ? Or am I missing something ?
Comparing dates with either equals() or compareTo() compares the times (hours, minutes, seconds, millis) as well as the dates. Your test is failing because myDate is midnight today, whereas now is a little later than that.
Your comparison is failing because you need to format now so that both dates have the same format and thus may be compared.
Or, if you prefer, you can convert dates into strings and perform the comparison:
String beginDate = "28/12/2011";
Calendar now = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String nowStr = df.format(new Date());
System.out.println("equals : " + beginDate.equals(nowStr));
Are you specifying the milliseconds when creating the dates? If you are, don't. So when creating the dates earlier, only specify the Day, Hour etc, not seconds/milliseconds.
And, change the SimpleDateFormat respectively. That "should" work.
Date object in Java is nothing but a number that represents milliseconds since January 1, 1970, 00:00:00 GMT. It doesn't have any attribute called day, date, month, year etc. That's because date, month, year varies based on the type of calendar and timezone. These attributes belong to Calendar instance.
So, if you have 2 Date objects and you want to compare day of month, month and year then you should create corresponding Calendar instance and compare them separately.
// Parse begin date
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date beginDate = dateFormat.parse(beginDateAsString);
// Create calendar instances
Calendar beginDateCalendar = Calendar.getInstance();
beginDateCalendar.setTime(beginDate);
Calendar todayCalendar = Calendar.getInstance();
// Check Equals
boolean dayEquals = todayCalendar.get(Calendar.DAY_OF_MONTH) == beginDateCalendar
.get(Calendar.DAY_OF_MONTH);
boolean monthEquals = todayCalendar.get(Calendar.MONTH) == beginDateCalendar
.get(Calendar.MONTH);
boolean yearEquals = todayCalendar.get(Calendar.YEAR) == beginDateCalendar
.get(Calendar.YEAR);
// Print Equals
System.out.println(dayEquals && monthEquals && yearEquals);
Above code is cumbersome for the current problem but explains how date operations must be done in JAVA.
If you just want to solve the equals problem you have mentioned then the code below will suffice:
String todayAsString = (new SimpleDateFormat("dd/MM/yyyy")).format(new Date());
System.out.println(beginDateAsString.equals(todayAsString));
If you are only going to be dealing with dates between the years 1900 and 2100, there is a simple calculation which will give you the number of days since 1900:
public static int daysSince1900(Date date) {
Calendar c = new GregorianCalendar();
c.setTime(date);
int year = c.get(Calendar.YEAR) - 1900;
int month = c.get(Calendar.MONTH) + 1;
int days = c.get(Calendar.DAY_OF_MONTH);
if (month < 3) {
month += 12;
year--;
}
int yearDays = (int) (year * 365.25);
int monthDays = (int) ((month + 1) * 30.61);
return (yearDays + monthDays + days - 63);
}
Thus, Date (only) comparison can be achieved by checking if the number of days since 1900 of the 2 dates are equal.
NOTE: The above method should have code added to check if the dates are outside the valid range (1/1/1900 - 31/12/2099) and throw an IllegalArgumentException.
And don't ask me where this calculation came from because we've used it since the early '90s.