Home > Net >  How can I can take in a valid date as a string but if not keep the default assigned byt the default
How can I can take in a valid date as a string but if not keep the default assigned byt the default

Time:09-17

I'm trying to create a calendar class in which I initial a default date. When a user creates the class the default Constructor is assigning the value "01-01-2012". If the user enters a valid date as a string parameter the second constructor will assign the new date.If not I would like the class to give a friendly warning this is not a valid date and go ahead and keep the default assignment.( eg. If the user enter "02/31/2012". This would throw the warning and go ahead and create the instance while setting the default to "01-01-2021".) I also created a method to set the date so this can be changed later once they give a valid date. How should i the second constructor in order to do this? Or is there a better more efficient process in order to do this?

import java.time.*;
import java.time.format.DateTimeFormatter;



public class CalendarDate {

    private String date;
    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMMM dd uuuu");
  
    //constructor sets date to January 1, 2012
    CalendarDate(){

       date = "01-01-2012";
    };

    /**
     *  Initializes object's chosen date
     * 
     * @param day - initializes day
     * @param month - initialazes month
     * @param year - initialazes year
     */
    public CalendarDate(String date){

        this.date = date;

    } // 1 - parameter Constructor


    /**
     * 
     *  Sets new date given to this object
     * 
     * @param date sets new date to object
     */
    public void setDate(String date){

        this.date = date;
    }

    /**
     * 
     * Returns objects set date.
     * 
     * @return Returns set date.
     */
    public String getDate(){

        LocalDate getDate = LocalDate.parse(date);
        String formattedDate = getDate.format(formatter);
        return formattedDate;
    }

    /**
     * 
     * Returns object's date
     * 
     * @return Returns object's date
     */
    public String getNextDate(){

        LocalDate dateTime = LocalDate.parse(date);
        LocalDate returnValue = dateTime.plusDays(1);
        String newNextDate = formatter.format(returnValue);
        return newNextDate;
     
    }

    /**
     *  Returns prior date from the object's given date.
     * 
     * @return
     */
    public String getPriorDate(){

        return " ";
    
    }

    /**
     *  Returns the day of the week from the object's given date.
     * 
     * @return
     */
    public String getDayOfWeek(){

        return " ";
    
    }



}


public class Calendar extends CalendarDate{

    public static void main(String[] args){

        CalendarDate testDate = new CalendarDate("06-07-1992");

       testDate.getDate();
        

    }
}

This is what I have so far and I'm wanting to use LocalDate and DateTimeFormatter. Anything will help.

CodePudding user response:

The format specified in the DateTimeFormatter must match the input string e.g.

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String strDate = "01-01-2012";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-uuuu", Locale.ENGLISH);
        LocalDate date = LocalDate.parse(strDate, dtf);
        System.out.println(date);

        // Output in a custom format
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM dd uuuu", Locale.ENGLISH);
        String formatted = formatter.format(date);
        System.out.println(formatted);
    }
}

Output:

2012-01-01
January 01 2012

ONLINE DEMO

Learn more about the modern Date-Time API* from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8 APIs available through desugaring and How to use ThreeTenABP in Android Project.

CodePudding user response:

I offer the following suggestions to your design. I think they will also fix your error as a side effect if you had one.

private String date;

Don’t keep your date as a string. Keep it as a LocalDate object. Just like you keep numbers in int variables and Booelan values in boolean variables, not in strings. So the declaration becomes:

private LocalDate date;

This obviously means we will have to change much of the code in your methods.

CalendarDate(){

   date = "01-01-2012";
};

In the above constructor you may use one of the of factory methods of LocalDate. For exmaple:

   date = LocalDate.of(2012, Month.JANUARY, 1);

You have got:

 * @param day - initializes day
 * @param month - initialazes month
 * @param year - initialazes year

It seems your Javadoc parameters don’t agree with your constructor here, and you need to fix them.

public CalendarDate(String date){

    this.date = date;

} // 1 - parameter Constructor

It can be convenient to have a constructor that takes a String argument. In your Javadoc comment remember to mention the expected format of the string. Since I have now changed date to be a LocalDate, you need to parse the string before assigning to date. I suggest that you let any DateTimeParseException propagate out of the method so the user knows if parsing goes wrong. Also in your Javadoc document that the method may throw:

 * @throws DateTimeParseException
 *   if the string is not in the expected format or does not denote a valid date

Further:

public void setDate(String date){

Again a method that is probably convenient and that will now need to parse the string. And throw an exception if appropriate.

public String getDate(){

    LocalDate getDate = LocalDate.parse(date);
    String formattedDate = getDate.format(formatter);
    return formattedDate;
}

You can now simplify the above method a bit since it no longer needs to parse the date, only to format it. The same holds true for at least one more method.

  • Related