Convert month name to Date range - java

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

Related

Parse date of after 20 years

I have a string like "1512". I need to convert it to a date 2015-12-31 23:59:59.
In that case, I am using Java Dateformat parse.
My code:
private static final dateformat = new SimpleDateFormat("yyMM");
public static boolean checkDate(String date){
Date date = dateformat.parse(date);
}
It can give date upto 20 years. When date is "3610", it gives, 1936, instead of 2036 (of the current century).
I think, you can manually parse the String and then create the Date object.
suppose:
public static void checkDate(String date) throws ParseException {
Calendar calendar = Calendar.getInstance();
int year = Integer.parseInt(date.substring(0, 2));
int month = Integer.parseInt(date.substring(2, 4));
calendar.setLenient(false);
int yearOfCentury = calendar.get(Calendar.YEAR);
int century = yearOfCentury - yearOfCentury % 100;
year = year + century;
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
System.out.println("Date +" + calendar.getTime());
}
If you are sure that the year should be always 2000+ then prefix the string with "20" manually and use the SimpleDateFormat as
private static final dateformat = new SimpleDateFormat("yyyyMM");
From the docs:
For parsing with the abbreviated year pattern ("y" or "yy"),
SimpleDateFormat must interpret the abbreviated year relative to some
century. It does this by adjusting dates to be within 80 years before
and 20 years after the time the SimpleDateFormat instance is created.
For example, using a pattern of "MM/dd/yy" and a SimpleDateFormat
instance created on Jan 1, 1997, the string "01/11/12" would be
interpreted as Jan 11, 2012 while the string "05/04/64" would be
interpreted as May 4, 1964.
The default behaviour of the YearMonth parser in Java 8 for 2 digit years is to start from 2000. So this would give you the result you expect:
YearMonth ym = YearMonth.parse("3610", DateTimeFormatter.ofPattern("yyMM"));
//ym = 2036-10
If you want a cut-off at a specific date (say you want 80-99 to be 1980-1999 and 0-79 to be 2000-2079) you can use a custom pattern.

How do I add 2 weeks to a Date in java? [duplicate]

This question already has answers here:
Modify the week in a Calendar
(4 answers)
Closed 5 years ago.
I am getting a Date from the object at the point of instantiation, and for the sake of outputting I need to add 2 weeks to that date. I am wondering how I would go about adding to it and also whether or not my syntax is correct currently.
Current Java:
private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private Date dateOfOrder;
private void setDateOfOrder()
{
//Get current date time with Date()
dateOfOrder = new Date();
}
public Date getDateOfOrder()
{
return dateOfOrder;
}
Is this syntax correct? Also, I want to make a getter that returns an estimated shipping date, which is 14 days after the date of order, I'm not sure how to add and subtract from the current date.
Use Calendar and set the current time then user the add method of the calendar
try this:
int noOfDays = 14; //i.e two weeks
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfOrder);
calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
Date date = calendar.getTime();
I will show you how we can do it in Java 8. Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 2 week to the current date
LocalDate next2Week = today.plus(2, ChronoUnit.WEEKS);
System.out.println("Next week: " + next2Week);
}
}
The output:
Current date: 2016-08-15
Next week: 2016-08-29
Java 8 rocks !!
Use Calendar
Date date = ...
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.WEEK_OF_MONTH, 2);
date = c.getTime();
Try this to add two weeks.
long date = System.currentTimeMillis() + 14 * 24 * 3600 * 1000;
Date newDate = new Date(date);
if pass 14 to this addDate method it will add 14 to the current date and return
public String addDate(int days) throws Exception {
final DateFormat dateFormat1 = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, addDays); // Adding 5 days
return dateFormat1.format(c.getTime());
}
Using the Joda-Time library will be easier and will handle Daylight Saving Time, other anomalies, and time zones.
java.util.Date date = new DateTime( DateTimeZone.forID( "America/Denver" ) ).plusWeeks( 2 ).withTimeAtStartOfDay().toDate();
If you are on java 8 you can use new date time api http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#plusWeeks-long-
if you are on java 7 or more old version of java you should use old api http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#add-int-int-

Creating java date object from year,month,day

int day = Integer.parseInt(request.getParameter("day")); // 25
int month = Integer.parseInt(request.getParameter("month")); // 12
int year = Integer.parseInt(request.getParameter("year")); // 1988
System.out.println(year);
Calendar c = Calendar.getInstance();
c.set(year, month, day, 0, 0);
b.setDob(c.getTime());
System.out.println(b.getDob());
Output is:
1988
Wed Jan 25 00:00:08 IST 1989
I am passing 25 12 1988 but I get 25 Jan 1989. Why?
Months are zero-based in Calendar. So 12 is interpreted as december + 1 month. Use
c.set(year, month - 1, day, 0, 0);
That's my favorite way prior to Java 8:
Date date = new GregorianCalendar(year, month - 1, day).getTime();
I'd say this is a bit cleaner than:
calendar.set(year, month - 1, day, 0, 0);
java.time
Using java.time framework built into Java 8
int year = 2015;
int month = 12;
int day = 22;
LocalDate.of(year, month, day); //2015-12-22
LocalDate.parse("2015-12-22"); //2015-12-22
//with custom formatter
DateTimeFormatter.ofPattern formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate.parse("22-12-2015", formatter); //2015-12-22
If you need also information about time(hour,minute,second) use some conversion from LocalDate to LocalDateTime
LocalDate.parse("2015-12-22").atStartOfDay() //2015-12-22T00:00
Java's Calendar representation is not the best, they are working on it for Java 8. I would advise you to use Joda Time or another similar library.
Here is a quick example using LocalDate from the Joda Time library:
LocalDate localDate = new LocalDate(year, month, day);
Date date = localDate.toDate();
Here you can follow a quick start tutorial.
See JavaDoc:
month - the value used to set the MONTH calendar field. Month value is
0-based. e.g., 0 for January.
So, the month you set is the first month of next year.
Make your life easy when working with dates, timestamps and durations. Use HalDateTime from
http://sourceforge.net/projects/haldatetime/?source=directory
For example you can just use it to parse your input like this:
HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate ); // will print in ISO format: 1988-12-25
You can also specify patterns for parsing and printing.

Comparing Age being populated using Selenium WebDriver

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

How to get last month/year in java?

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

Categories

Resources