how to save the datetime field to cosmosdb "SQL API / DocumentDb"? - java

I am sending the DateTime field from Java to documentdb/SQL API to cosmos db .
but it is saving the datetime as a number in documentdb , if i parse my datetime value to string then documentdb is showing correctly in string form , but i need it in datetime format in documentdb/SQL API .
What's the best practise to save datetime value in documentdb without parsing it to string?
What is the value of the date field in the documentdb collection if i not parse my datetime field to string ? for i.e "loggedAt": 1554207604392 is showing this number in documentdb . Can anyone please help me on this .
Document Db Item, highlighted field is the datetime which i am sending from java

What is the value of the date field in the documentdb collection if i
not parse my datetime field to string ?
The number is representing the number of elapsed seconds since January 1, 1970 which matches your datatime as Unix timestamps. Azure Cosmos DB's internal Timestamp (_ts) property follows this approach. You could refer to this document for details.
What's the best practise to save datetime value in documentdb without
parsing it to string?
From this feedback case,ms doesn't support native datetime type data.In this blog,the datetime data still was treated as String or Number.
As for unix timestamp query operations,You could follow my previous case :Convert TimeScript to Date in Azure CosmosDB SQL Query to convert unix timestamp to datetime by using UDF. Or get some clues from this case:Date Between Query in Cosmos DB

Related

Date Formating:I would like to obtain the following date format 25/11/1990 14:35 based on a Timestamp of format '0001-01-01-00.00.00.000000'

I would like to obtain the following date format 25/11/1990 14:35 based on a Timestamp of format '0001-01-01-00.00.00.000000'.
It needs to be done either via Angular 6 or Java 8.
Please provide any relevant solutions.
My Approach:
Timestamp timestamp = Timestamp.valueOf("1990-11-25 01:02:03.123456789")//Value from Db.
String str = timestamp.tostring();
str.substring();
This is helping me for displaying to the user but as I am converting it to a string I am unable to store it in DB Since DB will only store Timestamp format.
java.time and JDBC 4.2
I warmly recommend that you use java.time, the modern Java date and time API, for your date and time work, not the old Timestamp class. This example snippet includes how you retrieve the timestamp from your database and format it for the user:
DateTimeFormatter formatter = DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(Locale.forLanguageTag("pt"));
PreparedStatement query = yourDatabaseConnection.prepareStatement(
"select your_timestamp_column from your_table where id = 4;");
ResultSet rs = query.executeQuery();
if (rs.next()) {
OffsetDateTime dateTime
= rs.getObject("your_timestamp_column", OffsetDateTime.class);
String str = dateTime.format(formatter);
System.out.println(str);
}
Example output would be
25/11/1990 14:35
Please insert the language tag of your user where I put pt (for Portuguese). Or leave out the withLocale call to rely on the default locale of your JVM. And note the use of getObject() rather than getTimestamp().
I have used OffsetDateTime in the code based on the assumption that the datatype in your database is timestamp with time zone, which is what is recommended for timestamps. In this case you may also want to convert the timestamp to the user’s time zone before formatting it.
If the datatype is timestamp without time zone, instead use LocalDateTime in exactly the same manner.
Link: Oracle tutorial: Date Time explaining how to use java.time.

How to make sure mongo stores the date as is without converting to UTC? [duplicate]

Using Spring Boot 1.5.4.RELEASE and Mongo driver 3.4.2.
I want to store LocalDate in mongo DB, but I am facing a weird problem:
LocalDate startDate = LocalDate.now();
LocalDate endDate = LocalDate.of(2020,12,01);
System.out.println("---- StartDate : ---"+startDate);
System.out.println("-----End Date : ----"+endDate);
repository.save(new Person("Mehraj","Malik", startDate, endDate));
Output on console:
---- StartDate : ---2017-08-26
-----End Date : ----2020-12-01
But In MongoDb it is storing incorrect dates.
Following is the json from MongoDb:
"startDate" : ISODate("2017-08-25T18:30:00.000Z"),
"endDate" :ISODate("2020-11-30T18:30:00.000Z")
Also, I have noticed that the stored time is also incorrect according to Indian time.
Why the dates are correct on console but not in MongoDB and how to resolve this problem?
The mongo-java client for a date object returns as instance of
java.util.Date.
The problem could possibly be that while you save the startDate and the endDate value, its toString() method would probably use the JVM's default time zone to update the value.
The doc here states that The official BSON specification refers to the BSON Date type as the UTC datetime. and that could be the reason your LocalDateTime attributes were converted to the UTC time zone prior to being saved to the DB.
Also to avoid such confusion would suggest using the bson type timestamp to update date fields.
In the MongoDB Java Driver 3.7 release : http://mongodb.github.io/mongo-java-driver/3.7/whats-new/ we can see that the driver now support LocalDate :
JSR-310 Instant, LocalDate & LocalDateTime support
Support for Instant, LocalDate and LocalDateTime has been added to the driver.

Jersey JSON Date formatting POJO Mapping

I have date stored in mysql db as DATETIME and the value is stored in db as
"2016-09-09 15:56:26"
I wanted to display in same format, I am using Jersey 1.19 with POJOMapping and I used Date format in pojo, but the value shown in API is as:
"createdDt":1473454586000
What is the right approach to display correct date format in GET API, should I use String?

How to select by date only if field is a timestamp?

I have a database field timestamp without timezone, that has values like 2015-11-23 14:42:55.278.
Now I want to find database records with just using the date part 2015-11-13.
Is that possible?
Ideally using hibernate and spring.
I'm not sure if is the best way in performace terms, but you may search dates between 2015-11-23 00:00:00.000 and 2015-11-23 23:59:59.999
If you want to fetch only for day 2015-11-13 then you can fetch all records using between keyword and by using timestamp of start of day.
dateField between 2015-11-13:<time_of_beginning_of_day> AND 2015-11-14:<time_of_beginning_of_next_day>
or
dateField between 2015-11-13:<time_of_beginning_of_day> AND 2015-11-13:<time_of_end_of_day>
You can cast the column to a date, e.g:
Postgres specific:
the_timestamp_column::date = date '2015-11-13'
or (standard SQL)
cast(the_timestamp_column as date) = date '2015-11-13'
You can also "reduce" the timestamp to different levels using date_trunc()
http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC

Storing Java Date object in REDIS

I need to store a Java Date object in Redis. I'm using Jedis as my Redis client. How do I store a Date object in Redis and retrieve it using Java? Everything I see uses String and Integer values. However, I don't understand enough about this world to do this with a Date object.
How about converting the Date object to Epoch timestamp and converting it back to Date with any date format? This way you will not get into trouble with formatting errors..
//...convert date to epoch timestamp
Long time = new Date().getTime();
//...serialize it to a json object
job.addProperty("dateTime", time);
//...write it to redis
jedis.hset(KEY, field, job.toString());
//...retrieve the field and convert date with any format
model = gson.fromJson(jedis.hget(KEY, field), ModelClass.class);
//...print the date (suppose that the time field is of type Long)
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
System.out.println(format.format(model.getTime()));
Hope this helps.
You need to find a way to serialize the data and parse it later. Redis will only store strings, and Jedis doesn't provide serializers. This conversation has more information about your use case.

Categories