I am using GWT, java, iText to produce a PDF and want to reformat the date. However, this code, on the server side, results in the message "Connection failed" on the client side (there are no error messages in the log) and no output:
String storedName = " ";
DateTimeFormat sdf = DateTimeFormat.getFormat("dd-MM-yyyy");
for (final Transcript scoutNamesDescription : listymAwards) {
if (scoutNamesDescription.getSection().equals(storedName)){
table.addCell(" ");
}else{
storedName = scoutNamesDescription.getSection();
table.addCell(scoutNamesDescription.getSection());
}
table.addCell(scoutNamesDescription.getAwardName());
Date awardedDate = sdf.parse(scoutNamesDescription.getAwardedDate());
String awardedString = DateTimeFormat.getFormat("dd-MM-yyyy").format(awardedDate);
table.addCell(awardedString);
}
preface.add(table);
document.add(preface);
When I comment out the date reformatting this works.
I have tried replacing the reformatting with:
System.out.println(scoutNamesDescription.getAwardedDate());
formatedDate = StringUtils.substring(scoutNamesDescription.getAwardedDate(), 8, 2) +
StringUtils.substring(scoutNamesDescription.getAwardedDate(), 4, 4) +
StringUtils.substring(scoutNamesDescription.getAwardedDate(), 0, 2);
System.out.println(formatedDate);
And this also produces the same error between the two println.
Based on Andrei Volgin's reply I have the following:
String storedName = null;
DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy");
for (final Transcript scoutNamesDescription : listymAwards) {
if (scoutNamesDescription.getSection().equals(storedName)){
table.addCell(" ");
}else{
storedName = scoutNamesDescription.getSection();
table.addCell(scoutNamesDescription.getSection());
}
table.addCell(scoutNamesDescription.getAwardName());
Date awardedDate = df1.parse(scoutNamesDescription.getAwardedDate());
String awardedString = df2.format(awardedDate);
table.addCell(awardedString);
}
preface.add(table);
document.add(preface);
}
You cannot use GWT code on the server side. And in this case there is no need.
Use standard Java tools for formatting dates:
Convert java.util.Date to String
Related
I have been using selenium webdriver and chrome and logs recently. But any timestamp values are coming back in a weird date time stamp format. I've search all over, and I cannot figure what it is. Furthermore, other values besides timestamp (like requestId or walltime) are also in new unknown formats. What format is this and how can I get it into a normal (MM DD YYYY HH:MM:SS..) format?
timestamp was 2484894.662632 around June 23rd 2021, 10:53:23.118
timestamp was 2486019.900761 around June 23rd 2021, 11:12:01.277
timestamp was 2581839.545059 around June 24th 2021, 13:49:09.354
Example:
"requestId":"30432.634","timestamp":87693.142713,"type":"XHR","wallTime":1624556888.229531}
Code snippet:
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
flavorCapability.setCapability("goog:loggingPrefs", logPrefs);
driver.manage().logs().get(LogType.PERFORMANCE).getAll();
There is two way to get the desired result:
1) Simple way:
LogEntries entries = driver.manage().logs().get(LogType.PERFORMANCE);
for(LogEntry entry: entries){
System.out.println(entry.getTimestamp());
System.out.println(entry.getLevel());
System.out.println(entry.getMessage());
System.out.println(entry.toJson());
System.out.println(new Date(entry.getTimestamp()));
}
2) Second way to do it:
import org.json.JSONException;
import org.json.JSONObject;
LogEntries logs = driver.manage().logs().get("performance");
for (Iterator<LogEntry> it = logs.iterator(); it.hasNext();) {
LogEntry entry = it.next();
try {
JSONObject json = new JSONObject(entry.getMessage());
JSONObject message = json.getJSONObject("message");
String method = message.getString("method");
System.out.println(method);
if (method != null && "Network.responseReceived".equals(method)) {
JSONObject params = message.getJSONObject("params");
JSONObject response = params.getJSONObject("response");
JSONObject headers = response.getJSONObject("headers");
String timestamp = headers.getString("date");
String url = response.getString("url");
int status = response.getInt("status");
System.out.println("Response = " + response);
System.out.println("URL = "+ url);
System.out.println("Status Code = "+ status);
System.out.println("headers: " + response.get("headers"));
System.out.println("Timestamp: " + timestamp);
}
} catch (JSONException e) {
System.out.println(e.getMessage());
}
}
Ref: https://chromedevtools.github.io/devtools-protocol/tot/Network/
Note: Please provide the exact requirement, what exactly you want to get?
Subtracting the timestamp as seconds from the 3 datetimes you got these stamps, I could deduce that the timestamp means number of seconds that have passed since 16:38:25 +- 5 sec on the 25th of May 2021. All three timestamps agree that this is the origin.
Don't ask me why the origin is at that time. Maybe the computer booted at that time, or some number overflowed and started from 0 again.
Hello I am trying to store the birthdate of the user in database with the code below:
private void btnActionPerformed(java.awt.event.ActionEvent evt) {
String username = txtUserName.getText();
String password = txtPassword.getText();
String email = txtEmail.getText();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String birthdate = sdf.format(JDateChooser.getDate());
Users user = new Users();
user.setUserName(cin);
user.setPassWord(firstName);
user.setEmail(email);
user.setBirthDate(birthdate);
try {
int count = Users.getInstance().insert(user);
if(count == 1){
JOptionPane.showMessageDialog(null,"success");
reset();
}else{
JOptionPane.showMessageDialog(null,"Faild");
}
} catch (Exception ex) {
Logger.getLogger(AddNewPatient.class.getName()).log(Level.SEVERE, null, ex);
}
}
I got an error which says String connot be converted to Date in the line "user.setBirthDate(birthdate);"
Because the parameter birthdate is assigned as Date type in the encapsulation(setBirthDate)
is there any way to solve this issue, I am new in java programming and I am trying to improve my skills in java.
If this returns a Date:
JDateChooser.getDate()
And what you need is a Date, then don't convert it to a String. Just keep it as a Date:
Date birthdate = JDateChooser.getDate();
// later...
user.setBirthDate(birthdate);
Note that you can then also remove this line, since you're not using the variable it declares:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
In general you want to keep data types in their raw form pretty much as often as possible. Unless there's a specific need for something to be represented as a string (displaying it to the user, sending it over a serialized API of some kind, etc.) then just use the data as-is instead of converting it to something else.
After you get the date with JDateChooser.getDate(), you are immediately converting it to a string: sdf.format(JDateChooser.getDate());
You should store the returned Date from JDateChooser.getDate() as an actual Date object.
Date birthdate = JDateChooser.getDate();
Then you can use it in your other function directly:
user.setBirthDate(birthdate);
If you do need the date as a string for some other purpose (perhaps display to the user), you can store a formatted string version in a different variable:
String birthdateString = sdf.format(birthdate);
Otherwise, if you don't need a string version, you can delete the line where you create sdf.
I'm fetching the messages from authorized email but the problem is the separation of Subject, From, and To values from headers in java, I succeed in that below code is working fine but it is taking more time for separation, I have gone through so much Gmail API documentation but I didn't get the solution.
ListMessagesResponse listResponse = service.users().messages().list(user).setMaxResults(10L)
.setLabelIds(labelidlist).setQ(query).execute();
List<Message> listofmesssages = listResponse.getMessages();
HashMap<String, Object> msgsMap;
List messageslist = new ArrayList();
for (Message message : listofmesssages) {
Message fullmessage = service.users().messages().get("me", message.getId()).setFormat("full").execute();
msgsMap = new LinkedHashMap<String, Object>();
/*Adding threadid for threadid is required when delete operation has happen*/
msgsMap.put("threadid", message.getThreadId());
List<MessagePartHeader> headers = fullmessage.getPayload().getHeaders();
if (!headers.isEmpty()) {
for (MessagePartHeader header : headers) {
String name = header.getName();
msgsMap.put("msgid", message.getId());
if (name.equalsIgnoreCase("Subject")) {
subject = header.getValue();
msgsMap.put("subject", subject);
} else if (name.equalsIgnoreCase("From")) {
from = header.getValue().split("<")[0];
msgsMap.put("from", from);
} else if (name.equalsIgnoreCase("To")) {
to = header.getValue().split(" ")[0];
msgsMap.put("to", to);
} else if (name.equalsIgnoreCase("Date")) {
String date = header.getValue();
java.util.Date fecha = new java.util.Date(date);
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
Date date1;
date1 = (Date) formatter.parse(fecha.toString());
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/"
+ cal.get(Calendar.YEAR);
msgsMap.put("date", formatedDate);
}
}
}
messageslist.add(msgsMap);
}
return messageslist;
If you look at the message resource JSON, you can see that headers is an array of objects that contain properties name and value. There is no property key called To, or Subject. That's the reason the library you're using has no methods called getTo, or getSubject.
This makes sense, since headers might not always be the same ones.
Because of this, you cannot specifically fetch a certain header name.
Reference:
Users.messages
getHeaders()
I am trying to integrate a database with a web application that extracts event data from Google Calendar API which inputs the data into the database. The following code is identical to the Quickstart class provided by Google.
I basically want 'DateTime start' to be converted to 'long start'. I need the long value for SQL.
import com.google.api.client.util.DateTime;
// ...
DateTime now = new DateTime(System.currentTimeMillis());
Events events = service.events().list(calendarId)
.setTimeMin(now)
.setOrderBy("startTime")
.setSingleEvents(true)
.execute();
List<Event> items = events.getItems();
if (items.isEmpty()) {
System.out.println("No upcoming events found.");
} else {
System.out.println("Upcoming events");
for (Event event : items) {
DateTime start = event.getStart().getDateTime();
DateTime end = event.getEnd().getDateTime();
if (start == null) {
start = event.getStart().getDate();
}
System.out.printf("%s\n", start.toString());
Google has implemented the Rfc3339 parser in Google HTTP Client Library. You can try parsing it first and the use the DateTime.getValue() function to convert it into long.
You may also try using the DatetimeFormatter to format it to the way you want the value.
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
.withZone(ZoneId.of("UTC"));
public void convertDatetime() {
String timeStamp = "2019-05-24T11:32:26.553955473Z";
DateTime dateTime = DateTime.parseRfc3339(timeStamp);
long millis = dateTime.getValue();
String result = formatter.format(new Date(millis).toInstant());
I have a swing form which includes jXDatePicker to capture dates. When a date is not selected in the jXDatePicker an error is thrown when the trying to inserting the date into the database. Below is the error I am getting in Netbeans:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException.
Below is the code that is giving me errors:
String dateOpened, dateOfLastUpdate, dateOf1stDelinquency, dateOfLastPayment, dateClosed;
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateOpened = format.format(jXDatePicker7.getDate());
dateOfLastUpdate = format.format(jXDatePicker2.getDate());
dateOf1stDelinquency = format.format(jXDatePicker4.getDate());
dateOfLastPayment = format.format(jXDatePicker5.getDate());
dateClosed = format.format(jXDatePicker6.getDate());
String query2 = "insert into ACCOUNT (ACCOUNT_NUMBER,DATE_CLOSED ,DELINQUENCY_DATE, UPDATE_DATE,AMOUNT_OWING,"
+ "BALANCE,PAYMENT_HISTORY,ACCOUNT_STATUS,MONTHLY_PAYMENT,TERMS_DURATION,PRINCIPAL,CREDIT_LIMIT,"
+ "DATE_OPENED,PORTIFOLIO_TYPE,ACCOUNT_TYPE,NATIONAL_ID,COSIGNER_NATIONAL_ID)"
+ "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
PreparedStatement preparedStatement2 = con.prepareStatement(query2);
preparedStatement2.setString(1, acc_no);
preparedStatement2.setString(2, dateClosed);
preparedStatement2.setString(3, dateOf1stDelinquency);
preparedStatement2.setString(4, dateOfLastUpdate);
preparedStatement2.setDouble(5, amount_owing);
preparedStatement2.setDouble(6, current_balance);
preparedStatement2.setString(7, payment_history);
preparedStatement2.setString(8, account_status);
preparedStatement2.setDouble(9, monthly_payment);
preparedStatement2.setDouble(10, terms_duration);
preparedStatement2.setDouble(11, principal);
preparedStatement2.setDouble(12, credit_limit);
preparedStatement2.setString(13, dateOpened);
preparedStatement2.setString(14, portfolio_type);
preparedStatement2.setString(15, acc_type);
preparedStatement2.setString(16, national_id);
preparedStatement2.setString(17, cosigner_national_id);
preparedStatement2.executeUpdate();
Some dates are not required and applicable on some instances, therefore the user cannot select a date under such circumstances.
Check each individual JXDatePicker's date like jXDatePicker2.getDate() for null. Do not call format.format if that date does happen to be null. I get that exact same error you mentioned on the format.format line if the date is empty and enter is pushed. Instead, go for some default time, like new Date(0); meaning:
format.format(new Date(0));
Use following code and make sure that dateOpened column in database accept NULL values.
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
dateOpened = format.format(jXDatePicker7.getDate());
}else{
dateOpened = null;
}
If you don't want to insert NULL value then show error message as
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
if(jXDatePicker7.getDate() != null){
dateOpened = format.format(jXDatePicker7.getDate());
}else{
//error
}