Good morning! I need to capture the exact time a MessageInput
is submitted to handle scenarios where a user’s device is temporarily offline, causing delays with the backend.
What I Tried
This is the only solution I could find that works consistently, but it feels a bit awkward to me. Maybe there’s a more elegant way, such as using getElement().setAttribute()
?
private void handleMessageSubmit(MessageInput.SubmitEvent event, Scroller messageScroller) {
String jsCode = "const now = new Date();"
+ "const timestamp = now.toISOString();"
+ "const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;"
+ "return { timestamp, timezone };";
event.getSource().getElement().executeJs(jsCode).then(jsonString -> {
try {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString.toJson());
String timestamp = jsonNode.get("timestamp").asText();
String timezone = jsonNode.get("timezone").asText();
processSubmission(event.getValue(), timestamp, timezone, messageScroller);
} catch (Exception e) {
log.error("Failed to parse timestamp and timezone from JSON: {}", e.getMessage());
}
});
}
Other Posts I Looked At
According to this post, I can get the timezone offset using Page.getCurrent().getWebBrowser().getTimezoneOffset()
, but that doesn’t give me the time of the message’s submit event.
From this 2012 post, it seems like WebBrowser.getCurrentDate()
could get the user’s local date, which makes me wonder if there’s a way to get the current time of the browser. However, this still doesn’t fully solve my problem.
Docs Assistant
I also asked the Docs Assistant for a solution. It suggested:
messageInput.addSubmitListener(event -> {
String messageText = event.getValue();
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
items.add(new Message(messageText, timestamp, "User", "U", 1));
messageList.setItems(items);
Notification.show("Message sent at: " + timestamp, 3000, Notification.Position.MIDDLE);
});
However, this captures the time on the server side, not on the front end, right?
Docs Assistant Error
By the way, I’ve noticed that the Flow/Hilla select dropdown doesn’t seem to work correctly. Even when I have Flow selected, the assistant keeps giving me Hilla-like solutions unless I specifically include “with Vaadin Flow” in my query.