How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class - java

I want to save the date that a post was created in Firestore but I do not want to use the System time. Rather I want to use the server timestamp for accuracy sake. So I am using FieldValue.serverTimestamp() to get the server timestamp but the data type of my variable that holds this is Date. So How can I cast FieldValue.serverTimestamp() to Date?
Below is how my data class looks
data class MyModel( var timeStamp: Date,
constructor(): this(Calendar.getInstance().time, "")
}
PS: When I declare the timestamp as FieldValue in the data class, I get the error below:
java.lang.RuntimeException: No properties to serialize found on class
com.google.firebase.firestore.FieldValue

You get the following error:
java.lang.RuntimeException: No properties to serialize found on class com.google.firebase.firestore.FieldValue
Because FieldValue is not a supported data type. You should use the Date class or any other class that extends Date class, for example Timestamp class.
How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
There is no need to do any cast. In Java there is even no need to initialize the timeStamp field. To make it work, you should only use an annotation, as explained in my answer from the following post:
ServerTimestamp is always null on Firebase Firestore
Edit:
In Kotlin, you should initialize your timeStamp field in the constructor with a null value like this:
data class MyModel(
#ServerTimestamp
val timeStamp: Date? = null)

You can make use of an object to hold this value and later while using this value check the type of the object and make use of it. As of my knowledge the datatype returned is Long and you have to convert it manually to Data if you need.
The code for this will look like this,
replace this
data class MyModel( var timeStamp: Date,
with
data class MyModel( var timeStamp: Object,
And when using this timeStamp anywhere check it's type.
In java it will look like
if (timeStamp instanceof Long) {
// change Long to Date
//do this
}else{
//do something else
}
set the value for timeStamp as FieldValue.serverTimestamp() itself.

model class
data class MyModel(
#get: PropertyName("timestamp") #set: PropertyName("timestamp") var timestamp: Date= Date()
)
when initialize it;
val model = MyModel().apply{
this.timestamp to FieldValue.serverTimestamp()
}

Related

timestamp type changes to date type in hibernate query

I have an entity named A, which has a createdDate with this type #Temporal(TemporalType.TIMESTAMP).
I tried to retrieve all the rows having a certain createdDate. I attached a certain date to the request and I printed that date, it looks fine like "2021-02-11 12:14:02.425", which has all the values up to millisecond.
But the sql from hibernate, the value for createdDate in the where clause is set as '11-Feb-21'. Therefore, I do not find any rows because the createdDate is saved as 2021-02-11 12:14:02.425 in the db.
public Response getByCreatedDate(Request req) {
List<AResponse> aList = aRepository.findByIdAndCreatedDate(req.getId(), req.getCreatedDate());
}
I am new for Hibernate, I tried find some useful information about it but could not. Do I have to explicitly create a new Date with those specific date and time and send it to the method 'findByIdAndCreatedDate'? If anyone has the same experience, could you give some information about it?

Update with Server time For Spring Mongo

How to update entity with Mongo server time
Query query = new Query(new Criteria("id").is(user.getId()));
Update update = new Update().set("text", text)
.set("timeStamp", ??? );
This field should only be updated in one method
#LastModifiedDate It does not suit me?
timeStamp is LocalDateTime
You want either .currentDate() or .currentTimestamp() depending on your intended storage result.
Update update = new Update().set("text", text)
.currentDate("timeStamp");
Which actually corresponds to the $currentDate BSON update modifier and all the same usage, being of { $type: "date" } or { $type: "timestamp" } in it's options for the respective methods.
These are BSON Date values and therefore UTC Time.
Get the idea of Local time out of your head, since it has no business being stored in a database which can be accessed around the world.

Google Endpoint - java.sql.Timestamp - JSON

How to pass java.sql.Timestamp as JSON from front-end?
By default, I tried giving like 2015-09-29T12:30:00 in API explored.
It is not working.
Also, if anyone know, how to use #ApiTransformer for in-build java classes. OR is there an option to use this annotation at property level instead of POJO class level.
Answer:
Timestamp timestamp = new Timestamp(new Date().getTime());
ObjectMapper mapper = new ObjectMapper();
try {
String jacksonDate = mapper.writeValueAsString(timestamp);
System.out.println("JSON Timestamp: "+jacksonDate);
System.out.println("JAVA Timestamp: "+mapper.readValue(jacksonDate, Timestamp.class));
} catch (IOException e) {
e.printStackTrace();
}
output:
JSON Timestamp: 1443772585286
JAVA Timestamp: 2015-10-02 11:56:25.286
Even it accepts: yyyy-MM-DD'T'HH:mm:ss
I suggest you to think doing the opposite.
Let's say you get values from database to java beans (POJO) and serialize them to JSON objects. Print them out especially Timestamp values.
Then use the same format values as a short-cut answer.
On the other hand, in Jackson, I know that java.sql.Date accepts "long" values of time measure. Timestamp may use the same approach. "time in milliseconds" is a long value though.
On the other hand if you look for handling marshalling and unmarshalling of types in Rest systems you can check this out.
http://www.developerscrappad.com/2308/java/java-ee/rest-jax-rs/java-rest-jax-rs-2-0-how-to-handle-date-time-and-timestamp-data-types/

Null result for date object fetched from DB giving sysDate/current date on mapping to Java object

I fetched data from the oracle database through java code using a query similar to the below:
select min(specDate) from table
The result is supposed to be of type Date.
Since there was no specDate populated for any of the rows in the table, the result was null.
I used this query in my java code and mapped it to Date object using BeanPropertyRowMapper.
The result I got after mapping was the system date or the current date.
Not sure as to why the mapper returned current date instead of null.
Found the reason.
When the BeanPropertyRowMapper was provided with Date.class for mapping,
new Date() is called for instantiation of the class like for any object.
But for Date.class, new Date() returns sysDate.

JPA timestamp column and net.sf.json result from query

Inside my entity class I have a column of type timestamp:
#Column(name = "TESTD")
#Temporal(TemporalType.TIMESTAMP)
private Date test_date;
Inside my session bean I'm creating a select query which return a resultList, and then I'm creating from it a json object:
Query query = em.createNamedQuery("findAllTest");
List<entityClass> results = query.getResultList();
JSONSerializer.toJSON((List)results ,jsonConfig);
when creating the json object I want the timestamp column to be formatted (and not to return as object). How can this be done? how can I cast/format the timestamp column according to the date format I want? what is the best way to do this?
I guess you're using json-lib, based on the code sample, and I've never used it, but the javadoc shows that JsonConfig provides the following method:
public void registerJsonValueProcessor(Class propertyType,
JsonValueProcessor jsonValueProcessor)
Registers a JsonValueProcessor.
[Java -> JSON]
So I guess you could use that method, and register a processor for Calendar.class that would transform the Calendar object into a String using the format you want..
I create a second transient getter that returns the date as a String formatted how I want. It's a bit if a hack but works.

Categories

Resources