Java check two date as String - java

simply i have two variable as date which they are date as String, for example
"2016-11-30"
when i try to check two variable as this value i get false,
// serverDateTime value is: "2016-11-30"
// Utils.getCurrentDateTime() return: "2016-11-30"
private boolean checkCurrentDate(String serverDateTime) {
if (serverDateTime.equals(Utils.getCurrentDateTime())) {
return true;
} else {
return false;
}
}
public static String getCurrentDateTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(c.getTime());
}

Try to use moment.js
var stringDateOne = '2016-11-30';
var stringDateTwo = '2016-11-30';
var momentDateOne = moment(stringDateOne, 'YYYY-MM-DD');
var momentDateTwo = moment(stringDateTwo, 'YYYY-MM-DD');
if(momentDateOne.diff(momentDateTwo, 'days') == 0){
//date equal
}else{
//date not equal
}

hi The code is correct and is returning true for the above entries
public class HelloWorld {
public static void main(String[] args) {
String currDate = "2016-11-30";
HelloWorld hw = new HelloWorld();
System.out.println(hw.checkCurrentDate(currDate));
}
private boolean checkCurrentDate(String serverDateTime) {
if (serverDateTime.equals(HelloWorld.getCurrentDateTime())) {
return true;
} else {
return false;
}
}
public static String getCurrentDateTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(c.getTime());
}
}

Related

Calling a class without using Classname X = new Classname();

I have a class with set and get, and In another class.
However, if I use Classname X = new Classname(); I'll not be able to use previous information set before.
Here's part of the code:
public void BuscarID () throws Exception {
//THIS VOID IS FOR SEARCH
ConsumirWS2 http = new ConsumirWS2();
Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
Cliente2 u = new Cliente2();
Type ClienteType = new TypeToken<Cliente2>() {
}.getType();
int i = Integer.parseInt(InterfaceConsu2.jTextFieldID.getText());
u.setCad_pes_id(i);
String s = Integer.toString(u.getcad_pes_id());
String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Clienteid/get/"+s;
String json = http.sendGet(url, "GET");
u = g.fromJson(json, ClienteType);
System.out.println(json + ("\n"));
System.out.println(u.getcad_pes_nome() +("\n") + u.getCad_pes_apelido() +("\n") + u.getCad_pes_cpf() +("\n") + u.getCad_pes_data()+("\n"));
String Date1 = new SimpleDateFormat("dd-MM-yyyy").format(u.getCad_pes_data());
System.out.println(Date1);
InterfaceConsu2.jTextFieldNOME.setText(u.getcad_pes_nome());
InterfaceConsu2.jTextFieldAPELIDO.setText(u.getCad_pes_apelido());
InterfaceConsu2.jFormattedTextFieldCPF.setText(u.getCad_pes_cpf());
InterfaceConsu2.jFormattedTextFieldDATA.setText(Date1);
InterfaceConsu2.jTextFieldID.setText(s);
}
public void alterar () throws Exception {
//THIS VOID IS FOR EDITING THE INFORMATION GET BEFORE
ConsumirWS2 http = new ConsumirWS2();
Gson g = new GsonBuilder().setDateFormat("dd-MM-yyyy").create();
Cliente2 u = new Cliente2();
Type ClienteType = new TypeToken<Cliente2>() {
}.getType();
u.setCad_pes_nome(InterfaceConsu2.jTextFieldNOME.getText());
u.setCad_pes_cpf(InterfaceConsu2.jFormattedTextFieldCPF.getText());
u.setCad_pes_apelido(InterfaceConsu2.jTextFieldAPELIDO.getText());
int i = Integer.parseInt(InterfaceConsu2.jTextFieldID.getText());
u.setCad_pes_id(i);
//u.setCad_pes_id(InterfaceConsu2.jTextFieldID.getText());
SimpleDateFormat formatter = new SimpleDateFormat ("dd-MM-yyyy");
java.util.Date utilDate = null;
try {
utilDate = formatter.parse(InterfaceConsu2.jFormattedTextFieldDATA.getText());
} catch (ParseException ex) {
Logger.getLogger(InterfaceConsu2.class.getName()).log(Level.SEVERE, null, ex);
}
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
u.setCad_pes_data(sqlDate);
String json = g.toJson(u, ClienteType);
String url = "http://localhost:8080/clienteWebService/webresources/CadastroCliente/Cliente/alterar";
http.sendPost(url, json, "PUT");
}
and then I have the set and get class:
public class Cliente2 {
public String cad_pes_nome;
public String cad_pes_apelido;
private String cad_pes_cpf;
public int cad_pes_id;
public Date cad_pes_data;
public String getcad_pes_nome() {
return cad_pes_nome;
}
public void setCad_pes_nome(String cad_pes_nome) {
this.cad_pes_nome = cad_pes_nome;
}
public String getCad_pes_apelido() {
return cad_pes_apelido;
}
public void setCad_pes_apelido(String cad_pes_apelido) {
this.cad_pes_apelido = cad_pes_apelido;
}
public String getCad_pes_cpf() {
return cad_pes_cpf;
}
public void setCad_pes_cpf(String cad_pes_cpf) {
this.cad_pes_cpf = cad_pes_cpf;
}
public int getcad_pes_id() {
return cad_pes_id;
}
public void setCad_pes_id(int cad_pes_id) {
this.cad_pes_id = cad_pes_id;
}
public Date getCad_pes_data() {
return cad_pes_data;
}
public void setCad_pes_data(Date cad_pes_data) {
this.cad_pes_data = cad_pes_data;
}
}
Because I'm using Classname X = new Classname();, when I try to print my u.getcad_pes_nome or any other get, It's empty, There's a way to call Cliente2 without using Cliente2 u = new Cliente2(); or what I have to change in my classes?

How to set a predefined message in lblText.steText()

I want to got the String msg from where Exception is thrown in personAge method so it shows defined error for a person.
How do I get the message from throw new Invalid..("the message");
to the lable?
This is code in my controler
#FXML
void btnRegister(ActionEvent event) {
String name = txtName.getText();
String email = txtEmail.getText();
String phonenr = txtPhonenr.getText();
int year = Integer.parseInt(txtYear.getText());
int month = Integer.parseInt(txtMonth.getText());
int day = Integer.parseInt(txtDay.getText());
boolean validateName = PersonValidator.checkName(name);
boolean validateEmail = PersonValidator.checkEmail(email);
boolean validatePhonenr = PersonValidator.checkPhonenr(phonenr);
try{
PersonAge.personAge(year);
}catch (InvalidAgeException msg){
lblResult.setText(msg);
}
}
And this is where exceptions is thrown :
public class PersonAge {
public static int personAge(int year) throws InvalidAgeException {
Date date = new Date();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Norway"));
cal.setTime(date);
int thisYear = cal.get(Calendar.YEAR);
int age = thisYear - year;
if(age <=0 || age > 120){
throw new InvalidAgeException("Age is invalid! Try again");
}
return age;
}
}
You just need to call getMessage() on the exception: lblResult.setText(msg.getMessage());

Is there a simple way to check fields for null with if else?

I have a class with three pairs of Date fields.
public static final class Filter {
private final Date startDateFrom;
private final Date startDateTo;
private final Date endDateFrom;
private final Date endDateTo;
private final Date regDateFrom;
private final Date regDateTo;
public Filter(Date startDateFrom, Date startDateTo,
Date endDateFrom, Date endDateTo,
Date regDateFrom, Date regDateTo) {
this.startDateFrom = startDateFrom;
this.startDateTo = startDateTo;
this.endDateFrom = endDateFrom;
this.endDateTo = endDateTo;
this.regDateFrom = regDateFrom;
this.regDateTo = regDateTo;
}
}
So I need to check that at least one pair has both not null Dates and check that DateFrom is before or equals DateTo for all not-null dates.
I've made this to check if there is at least one pair:
public boolean allDatesMissing() {
if (startDateFrom != null && startDateTo != null) {
return false;
} else if (endDateFrom != null && endDateTo != null) {
return false;
} else if (regDateFrom != null && regDateTo != null) {
return false;
}
return true;
}
And this to check fromDate is before toDate:
public void checkDates(Date from, Date to) throws RequestException{
if (from != null) {
if (to != null) {
if (from.after(to)) {
throw new MyException(INCORRECT_DATES_PERIOD);
}
} else {
throw new MyException(MISSING_PARAMETER);
}
} else if (to != null){
throw new MyException(MISSING_PARAMETER);
}
}
Is there any simplier way to do the same?
You have declared the Filter class static..Then it should be a inner class..
package demo;
import java.util.Date;
public class FilterDemo {
public static void main(String[] args) throws Exception {
Filter f = new Filter(new Date(2017, 01, 01), new Date(2017, 02, 01),
null, null, null, null);
}
public static final class Filter {
private final Date startDateFrom;
private final Date startDateTo;
private final Date endDateFrom;
private final Date endDateTo;
private final Date regDateFrom;
private final Date regDateTo;
// dateCounter will maintain the count of correct date pair
public static int dateCount = 0;
public Filter(Date startDateFrom, Date startDateTo, Date endDateFrom,
Date endDateTo, Date regDateFrom, Date regDateTo)
throws Exception {
this.startDateFrom = startDateFrom;
this.startDateTo = startDateTo;
isExist(startDateFrom, startDateTo);
this.endDateFrom = endDateFrom;
this.endDateTo = endDateTo;
isExist(endDateFrom, endDateTo);
this.regDateFrom = regDateFrom;
this.regDateTo = regDateTo;
isExist(regDateFrom, regDateTo);
// throw exception after initializing 3 pair,if count is still 0
if (dateCount == 0)
throw new Exception("All pairs are null");
}
public static void isExist(Date from, Date to) throws Exception {
if (from != null && to != null) {
checkDates(from, to);
}
}
public static void checkDates(Date from, Date to) throws Exception {
if (from.getTime() > to.getTime()) {
throw new Exception("INCORRECT_DATES_PERIOD");
}
//increase dateCount if date pair is correct
dateCount++;
}
}
}

Parsing Date in string Database using getters/setters

I'm trying to get a Date to Gmt+7 from listview Adapter :
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
_teamlist.clear();
db = new DBHelper(getApplicationContext());
db.getWritableDatabase();
ArrayList<TeamModel> team_list = getTeams2();
for (int i = 0; i < team_list.size(); i++) {
String tdate = team_list.get(i).getTeamdate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+7"));
Date datex = null;
try {
datex = sdf.parse(tdate);
} catch (ParseException e) {
e.printStackTrace();
}
TeamModel _TeamModel = new TeamModel();
_TeamModel.setTeamdate(datex); ///// here the probleme !!!!!
_teamlist.add(_TeamModel);
}
}
in this line '_TeamModel.setTeamdate(datex)' the error : "setTeamdate java.lang.String in TeamModel cannot be applied to java.util.Date "
My get/set class TeamModel:
public class TeamModel {
public String teamdate="";
....
public String getTeamdate() {
return teamdate;
}
public void setTeamdate(String teamdate) {
this.teamdate = teamdate;
}
}
i tried to change teamdate in this class to date from string but it mess up my DBHelper
thanks to "mithrop" for his help, this's what i did to fix the problem :
String tname = team_list.get(i).getTeamname();
String topponent = team_list.get(i).getTeamopponent();
String tdate111 = team_list.get(i).getTeamdate();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+9"));
Date datex = null;
try {
datex = sdf.parse(tdate111);
} catch (ParseException e) {
e.printStackTrace();
}
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String tdate = sdf.format(datex);
System.out.println(tdate);
TeamModel _TeamModel = new TeamModel();
_TeamModel.setTeamname(tname);
_TeamModel.setTeamopponent(topponent);
_TeamModel.setTeamdate(tdate);
_teamlist.add(_TeamModel);

Setting attribute to the option of DropDownChoice

I have a DropDownChoice:
DropDownChoice dateSpanChoice = new DropDownChoice("dateSpan", new PropertyModel(getModel(), "dateSpan"), dateSpans, new IChoiceRenderer() {
private static final long serialVersionUID = 10105L;
#Override
public String getIdValue(Object object, int index) {
return ((DateSpan) object).getId() + "";
}
#Override
public Object getDisplayValue(Object object) {
DateTime today = new DateTime();
DateTime currentDate = new DateTime(today.getYear(), today.getMonthOfYear(), today.getDayOfMonth(), 0, 0, 0, 0);
DateSpan dateSpan = (DateSpan) object;
DateTime fromDate = dateSpan.getFromDate();
DateTime toDate = dateSpan.getToDate();
boolean currentDateIsEqualOrAfterFromDate = currentDate.isEqual(fromDate) | currentDate.isAfter(fromDate);
boolean currentDateIsEqualOrBeforeToDate = currentDate.isEqual(toDate) | currentDate.isBefore(toDate);
boolean currentDateBelongsToCurrentRange = currentDateIsEqualOrAfterFromDate & currentDateIsEqualOrBeforeToDate;
if (currentDateBelongsToCurrentRange) {
return ((DateSpan) object).getDisplayValue() + " *";
} else {
return ((DateSpan) object).getDisplayValue();
}
}
}) {
private static final long serialVersionUID = 10106L;
protected CharSequence getDefaultChoice(final Object selected) {
CharSequence charSequence = super.getDefaultChoice(selected);
System.out.println("=============================================================");
//System.out.println(charSequence);
//THIS CHARSEQUENCE IS RENRING EMPTY STRING
if(StringUtils.isBlank(charSequence.toString())) {
System.out.println("CHARSEQUENCE IS BLANK");
} else {
System.out.println("CHARSEQUENCE IS NOT BLANK");
}
return charSequence;
}
};
dateSpanChoice.setNullValid(false);
I am trying to add style="background-color: red" to the selected option. So I am overriding getDefaultChoice() but as you can see it is commented in code the CharSequence is empty.
Is there any way to set an attribute to a particular option of DropDownChoice?
Thanks and Regards.
Note: the DateTime is Joda time
You need Select/SelectOption instead of DropDownChoice for more complex uses of element.
Have a look at the behavior package in Wicket.
You can use the AttributeAppender-class for instance.

Categories