Closed bytecod3r closed 3 years ago
First, you don't get a string by calling clock.currentTime()
but an object of type net.time4j.Moment
. You can store this moment in a database in various ways.
a) converting to a string compatible with ISO-8601-standard (just call toString()
b) converting to a java.util.Date
or a long
, see the TemporalType-API
The first method has the advantage to also save micro- or nanoseconds and even leap seconds (as ISO-8601-string) while the second approach can use standard JDBC-methods.
When loading from the database, the method a) requires a parser after you have got the string. Such a parser is predefined in Time4J, see the Iso8601Format-API.
Once you have obtained a Moment
you can easily get the local timestamp by specifying either a concrete time zone or the system time zone. Finally you can format/print such a timestamp using a ChronoFormatter
with your desired locale and pattern. Example:
String databaseISO = ...; // from the db
Moment m = Iso8601Format.EXTENDED_DATE_TIME_OFFSET.parse(databaseISO);
PlainTimestamp localTSP = m.toLocalTimestamp();
String s = ChronoFormatter.ofTimestampPattern("dd/MM/yyyy HH:mm:ss", PatternType.CLDR, Locale.getDefault()).print(localTSP);
You can even directly print a moment using:
String s = ChronoFormatter.ofMomentPattern("dd/MM/yyyy HH:mm:ss", PatternType.CLDR, Locale.getDefault(), Timezone.ofSystem().getID()).print(m);
Hi there,
I have such a situation that I need to get time from UTC with below code -
then the variable date will be saved in database as string. I am retrieving the date back from the database again in some other part of the code, but I want it to be converted to local timezone of the machine that the app is running, what ever time zone is the machine, it should get that string and convert the utc to that timezone. Is that possible?
I was trying to look into the parse function but I had no luck in implementing it.
Another question - How can I convert such a timstamp "2020-09-24T04:16:57,606346" to "dd/MM/yyyy HH:mm:ss" ?
Appreciate any hint or even better, if possible to give me an small snippet of code that works.
Thank you!