How to enter a date using Calendar?

0

I need to enter a date that has day, month and year, by keyboard, using the class Calendar, which method I call, of this class.

This is the code:

package models;
import java.util.Calendar;

public class User{
    protected EnumGenderUser gender;
    protected Calendar birthDate;
    protected String password;
    protected EnumCountry country;
    protected String email;

public User (EnumGenderUser gender, Calendar birthDate, String password, EnumCountry country, String email){
    this.setGender(gender);
    this.setBirthDate(birthDate);
    this.setPassword(password);
    this.setCountry(country);
    this.setEmail(email);
}

@Override
public String toString(){
    return super.toString();
}


//--------------------------------Setters------------------------------------------

public void setGender(EnumGenderUser gender){
    this.gender = gender;
}
public void setBirthDate(Calendar birthDate){
    this.birthDate = birthDate;
}
public void setPassword(String password){
    this.password = password;
}
public void setCountry(EnumCountry country){
    this.country = country;
}
public void setEmail(String email){
    this.email = email;
}
//--------------------------------Getters------------------------------------------

public EnumGenderUser getGender(){
    return this.gender;
}
public Calendar getBirthDate(){
    return this.birthDate;
}
public String getPassword(){
    return this.password;
}
public EnumCountry getCountry(){
    return this.country;
}
public String getEmail(){
    return this.email;
}
}

Here the class Daughter:

 package models;
 import java.util.Calendar;

public class Admin extends User{
private String name;
private String occupation;
private int id;

public Admin(String name, String occupation, int id, EnumGenderUser gender, Calendar birthDate, String password, EnumCountry country, String email){
    super(gender, birthDate, password, country, email);
    this.setName(name);
    this.setOccupation(occupation);
    this.setId(id);
}
@Override
public String toString(){
    String formatLine = "%1$-20s %2$-15s %3$-10s %4$-9s %5$-9s %6$-10s %7$-10s %8-30s";
    String adminLine = String.format(formatLine, name, occupation, id, gender, birthDate, password, country, email);
    return adminLine;
}
//--------------------------------Setters------------------------------------------

public void setName(String name){
    this.name = name;
}
public void setOccupation(String occupation){
    this.occupation = occupation;
}
public void setId(int id){
    this.id = id;
}
//--------------------------------Getters------------------------------------------

public String getName(){
    return this.name;
}
public String getOccupation(){
    return this.occupation;
}
public int getId(){
    return this.id;
}
}

The Enumerated:     package models;

public enum EnumGenderUser{
FEMENINO, MASCULINO;
}
package models;
public enum EnumCountry{
COLOMBIA, VENEZUELA, ARGENINA, CHILE, ECUADOR;
}

and the test:

package test;
import models.Admin;
import models.EnumCountry;
import models.EnumGenderUser;
import java.util.Calendar;

public class TestModels{

public static void main(String[] args){
    Admin adminObj = new Admin("Juan", "Diseñador", 64335, EnumGenderUser.MASCULINO, calendar.set(1990, 04, 12), "Qwerty123", EnumCountry.COLOMBIA, "[email protected]");
    System.out.println(adminObj.toString());
}

}

    
asked by Yeferson Gallo 03.09.2016 в 19:01
source

2 answers

1

What you are essentially looking for is to convert a text string or String to an object Date , and then you must send this Date object to your Calendar .

To do this, you can use the following code using SimpleDateFormat :

//lectura de entrada de teclado almacenada en String
Scanner scanner = new Scanner(System.in);
System.out.print("Ingrese fecha (yyyy-mm-dd): ");
String fechaString = scanner.nextString();
//crear el objeto SimpleDateFormat que permite
//convertir entre String y Date
//el formato es importante
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//convertimos el String en un Date
Date fecha = sdf.parse(fechaString);
//inicializamos el objeto Calendar
Calendar calendario = Calendar.getInstance();
//colocamos la fecha en nuestro objeto Calendar
calendario.setTime(fecha);
    
answered by 03.09.2016 в 19:54
0

Another possible way is to use the class DateTime de Joda The previous answer is already good, it is only by culturilla.

EJ:

/**
     * Esta función estática devuelve la fecha actual dependiento de una localización 
     * geográfica y un numero de dias a sumarle 
     * 
     * Localizaciones geográficas disponibles:
     * Continente/Ciudad ex: ==> Europe/Madrid || Europe/London || Asia/Jakarta ..........
     *  
     * <b> Si pasamos uns localización nula o vacia por defecto cogeremos la fecha de la locaclización Europe/Madrid</b> 
     * new DateTime(DateTimeZone.forID(localization)).plusDays(numDays).toDate();
     * Ex:
     * new DateTime(DateTimeZone.forID("Europe/Madrid")).plusDays(10).toDate();
     * 
     * mejoras añadidas a petición de la camorra(Francesco) 
     * si la fecha resultante cae en sábado o domingo lo pasamos a lunes. 
     * 
     * 
     * @param numDays número de dias a sumar a la fecha actual   si pasamos un 0 devuelve la fecha actual 
     * 
     * @param localization Continente/Ciudad
     *  
     * @return la fecha actual más el número de dias pasado por el parámero numDays tipo de fecha  {@link Date}   
     */
    public static Date returnDateTodayPlusDays(int numDays, String localization){

        if(!StringUtils.hasText(localization)){
            localization = "Europe/Madrid";
        }
        DateTime dateTime = new DateTime(DateTimeZone.forID(localization)).plusDays(numDays);
        //si queremos ver el dia 'texto' de la semana (new DateTime(DateTimeZone.forID(localization)).plusDays(numDays).dayOfWeek().getAsText();
        //para ver el dia en forma numérica entiendase 1 = lunes 7 = domingo(new DateTime(DateTimeZone.forID(localization)).plusDays(numDays).getDayOfWeek());
        if(dateTime.getDayOfWeek() == DateTimeConstants.FRIDAY){
            return new DateTime(DateTimeZone.forID(localization)).plusDays(numDays+3).toDate();
        }else if(dateTime.getDayOfWeek() == DateTimeConstants.SATURDAY){
            return new DateTime(DateTimeZone.forID(localization)).plusDays(numDays+2).toDate();
        }else{
            return new DateTime(DateTimeZone.forID(localization)).plusDays(numDays).toDate();
        }
    }

And finally you set the calendar as you mentioned @Luigi.

Calendar calendario = Calendar.getInstance();
calendario.setTime(returnDateTodayPlusDays(0, "la que sea"));
    
answered by 05.09.2016 в 17:56