Thursday, 16 June 2016

Date and time utilities in Java

Adding or subtracting the specific duration from the date

static Calendar calculateDate(String date) {

        int durationToBeAddedOrSubtracted;
        Calendar newDate = Calendar.getInstance();

        //-20 years
        durationToBeAddedOrSubtracted = Integer.parseInt(date.split(" ")[0]);
        if (date.toLowerCase().contains("months")){
            newDate.add(Calendar.MONTH, durationToBeAddedOrSubtracted);
        } else if (date.toLowerCase().contains("years")){
            newDate.add(Calendar.YEAR, durationToBeAddedOrSubtracted);
            newDate.add(Calendar.DATE, durationToBeAddedOrSubtracted);

        return newDate;

Getting the parts from a date in Java.

public void getDateParts(Calendar date){
        String day = String.valueOf(date.get(Calendar.DAY_OF_MONTH));
        String month = String.valueOf(date.get(Calendar.MONTH)+1);
        String year = String.valueOf(date.get(Calendar.YEAR));

        if (day.length()==1){
                    day = "0"+day;
        if (month.length()==1){
                  month = "0"+month;

Creating Calendar object from the date parts in Java.

           int day = Integer.parseInt(dob[0]);
            int month = Integer.parseInt(dob[1])-1;
            int year = Integer.parseInt(dob[2]);

            Calendar newDate = Calendar.getInstance();
            newDate.set(year, month, day, 0, 0);

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at

No comments:

Post a Comment

Buy Best Selenium Books