Parsing Date in string Database using getters/setters - java

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

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?

Java check two date as String

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

Unparsable date exception: string to java.sql.date

I have a problem with parsing a string to sql.date
This code works in my project only the first time, it will parse the date normally, but second time it throws exception.
I printed the date the function receives and it is the same format, for example 02.02.2016 was okey, I only changed month to 02.04.2016 and the exception was raised.
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
private final String sqldateFormat = "yyyy-mm-dd";
public java.sql.Date changeDate(String date) {
String newDate = "";
try {
java.util.Date d = dateFormat.parse(date);
dateFormat.applyPattern(sqldateFormat);
newDate = dateFormat.format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return java.sql.Date.valueOf(newDate);
}
Try this
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
private final SimpleDateFormat sqldateFormat = new SimpleDateFormat("yyyy-mm-dd");
public java.sql.Date changeDate(String date) {
String newDate = "";
try {
java.util.Date d = dateFormat.parse(date);
newDate = sqldateFormat.format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return java.sql.Date.valueOf(newDate);
}
Because during the fisrt execution you are modifying the pattern of the SimpleDateFormat it won't be able to parse the second date.
dateFormat.applyPattern(sqldateFormat); will modify the pattern to "yyyy-mm-dd" and then parsing 02.04.2016 will throw an exception.
this is because you change pattern of dateFormat.
This will work:
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
private final SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd");
public java.sql.Date changeDate(String date) {
String newDate = "";
try {
java.util.Date d = dateFormat.parse(date);
newDate = sqlFormat.format(d);
} catch (Exception e) {
e.printStackTrace();
}
return java.sql.Date.valueOf(newDate);
}
Apparently, this will work for the first run, but not for the second. Your problem is that you call applyPattern(), so it'll expect the new dates in sql date format only.
Here is a little better code:
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
private final SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd");
public java.sql.Date changeDate(String date) {
String newDate = "";
try {
java.util.Date d = dateFormat.parse(date);
newDate = sqlFormat.format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return java.sql.Date.valueOf(newDate);
}
Don't use valueOf().
If you have a java.util.Date and want a java.sql.Date (or java.sql.Timestamp), use the Date(long date) constructor:
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Also, don't catch exceptions and continue execution without handling it (printing it is not handling it).
Meaning that your code should be:
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
public java.sql.Date changeDate(String date) {
try {
return new java.sql.Date(dateFormat.parse(date).getTime());
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid date: " + date);
}
}
Warning: SimpleDateFormat is not thread-safe:
Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Java date parse string (Unparseable date)

i have these two parts of code.
Adding to the arraylist doesn't work, f arrylist is always empty. In the output debug window, the only message that i receive is Unparseable date: "2014-12-09 00:00:00.0" for each Fattura.
private ArrayList<Fattura> getFatture() throws SQLException {
String localDb;
String unformattedQuery;
ArrayList<Fattura> ftt = new ArrayList<Fattura>();
if (this.serviceSelection.getSelectedItem() == "Energia") {
localDb = EmailCheckerGUI.DbEnergia;
unformattedQuery = ServiceQuery.RECUPERAFATTUREENERGIA.getQuery();
} else {
localDb = EmailCheckerGUI.DbGas;
unformattedQuery = ServiceQuery.RECUPERAFATTUREGAS.getQuery();
}
DbHandlerContext db = new DbHandlerContext(new SqlServerConcrete(EmailCheckerGUI.user, EmailCheckerGUI.pwd, localDb));
String formattedQuery = String.format(unformattedQuery,
BillIntervalContainer.getFormattedMinDataFatt("MM/dd/yyyy"),
BillIntervalContainer.getFormattedMaxDataFatt("MM/dd/yyyy"),
BillIntervalContainer.minFattNumber, BillIntervalContainer.maxFattNumber);
ResultSet r = db.executeQuery(formattedQuery);
while (r.next()) {
try {
boolean addingelement = false;
String ioError = "";
try {
addingelement = ftt.add(new Fattura(r.getInt("id"), r.getString("servizio"), r.getString("email"),
r.getString("denominazione"), r.getString("data_fattura"), r.getString("data_scadenza"), r.getString("path_fattura"),
r.getInt("inviato"), r.getString("report"), r.getInt("numero_fattura"), r.getInt("id_documento")));
} catch (IOException ex) {
Logger.getLogger(EmailCheckerGUI.class.getName()).log(Level.SEVERE, null, ex);
ioError = ex.getMessage();
}
if (!addingelement) {
if (!"".equals(ioError)) {
addToLog("Impossibile aggiungere alla lista di invii la fattura numero " + r.getString("numero_fattura"));
} else {
addToLog("Impossibile aggiungere alla lista di invii la fattura numero " + r.getString("numero_fattura") + ": " + ioError);
}
} else {
System.out.println(r.getString("numero_fattura"));
}
} catch (ParseException ex) {
System.out.println(ex.getMessage());
}
}
return ftt;
}
and
Fattura( int id, String service, String email,
String name, String dateBill, String dateScad, String path,
int sent, String report, int billNumber, int idDocument) throws ParseException, IOException{
this.id = id;
this.service = service;
this.email = email;
this.name = name;
this.path = path;
this.report = report;
this.sent = sent;
this.billNumber = billNumber;
this.dateBill = new SimpleDateFormat("yyyy-MM-dd").parse(dateBill);
this.dateScad = new SimpleDateFormat("yyyy-MM-dd").parse(dateScad);
this.idDocument = idDocument;
this.pdfDocument = new PdfValidator(null, this.name, dateBill, String.valueOf(this.billNumber), String.valueOf(0), this.path);
}
Any idea of where i'm wrong?
Thanks
You are using week year : YYYY instead of year yyyy. Please take a look at the SimpleDateFormat documentation. You'll find all the patterns and some usefull examples.
Now yyyy-MM-dd will only parse 2014-12-09. If you have also time after date you should use something like :
yyyy-MM-dd HH:mm:ss.S
Or You can use .format instead of .parse :
this.dateBill = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
but watch out that MM can't be lowercase.

Convert JCalendar event c.getTime() to SimpleDateFormat

I want to convert the selected date into the format"dd-MM-yyyy" because c.getTime returns "Sun Mar 3 12:34:46 IST 2013"
private class MyDateListener implements DateListener {
public void dateChanged(DateEvent e) {
Calendar c = e.getSelectedDate();
if (c != null) {
try {
SimpleDateFormat parser = new SimpleDateFormat(c.getTime().toString());
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date;
date = parser.parse(date1);
output = formatter.format(date);
System.out.println(output);
} catch (ParseException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("No time selected.");
}
}
}
Do you want:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(sdf.format(c.getTime());
The getTime() function actually returns a date, which you can pass to your formatter, so there is no need to parse it.

Categories