How to represent a Calendar date in a json object using springboot - java

I have this following json object:
{
"username":"test",
"customerName":"test",
"accessReasons":"tes",
"leaseHours":"8"
}
This represents the time a certain user has to do a certain task (which is the sysdate + the leaseHours)
On my controller, I create an object with the information that I receive in that json:
thatObject obj=new thatObject (jsonObjectFromPostBody)
By doing that, an instance of thatObject is created this way:
public thatObject(thatObject aci) {
this.username=aci.getUsername();
this.customerName=aci.getCustomerName();
this.accessReasons=aci.getAccessReasons();
this.beginDate= new GregorianCalendar();
long sum=beginDate.getTimeInMillis()+aci.getLeaseHours().getTimeInMillis();
this.endDate=(Calendar)beginDate.clone();
this.endDate.setTimeInMillis(sum);
}
As you can see, my endDate is the enitial date + the time that the user has permissions to be active(which in this case is 8 hours)
But my problem is that I am using calendar and I cant represent those 8 hours on my json object, so when Im calculating the endTime it will be 0, how can I represent those 8 hours on my json or sum those 8 hours to my beginDate variable?

Why don't you just change the type of leaseHours property to Integer in thatObject?
In that case you can do something like this:
long sum=beginDate.getTimeInMillis() + aci * 60 * 60 * 1000;

Related

How to insert date in mongo db from java

There are many similar questions asked. But not exactly similar to the issue i am facing. I have seen almost all the questions and answers around it
So the problem is
I got to insert a date field in my mongo collection
But I can't access the collection directly. I got to use a service. The service takes a string and returns me oid.
So once i construct the BasicDBObject I call toString on it and pass it on to my service.. I even tried inserting it directly in a test collection and mongo is complaining.
BasicDBObject document = new BasicDBObject();
long createdAtSinceEpoch = 0;
long expiresAtSinceEpoch = 0;
createdAtSinceEpoch = System.nanoTime();
Date createdAt = new Date(TimeUnit.NANOSECONDS.toMillis(createdAtSinceEpoch));
document.append("createdAt", createdAt);
expiresAtSinceEpoch = createdAtSinceEpoch + +TimeUnit.SECONDS.toNanos(30);
Date expiresAt = new Date(TimeUnit.NANOSECONDS.toMillis(expiresAtSinceEpoch));
document.append("expiresAt", expiresAt);
service.storeRecord(document.toString());
and the generated JSON String looks like
{
"createdAt": {
"$date": "2015-09-01T20:05:21.641Z"
},
"expiresAt": {
"$date": "2015-09-01T20:05:51.641Z"
}
and Mongo complains that
Unable to parse JSON : Date expecting integer milliseconds, at (3,17)
So If i pass milliseconds alone instead of date object in the document.append() method then it DOES NOT recognize this field as date and considers it as String but inserts into the collection
I need 2 things
1) I want the data to be inserted
2) I am planning to expire that row by adding an index to the expiresAt field. So I want mongo to recognize that its a date field
JSON makes a difference between a numeric field and a text field containing a number. The latter one is only recognized as a String; I assume that this is what you did when you thought you were giving your service the date as an integer. Unfortunately you didn’t show us the relevant code.
When I save the Date info as a non String format, I annotate the field in my DTO as below. This helps the MongoDB know that the field is to be treated as an ISO date which then would be useful for making range search etc.,
#DateTimeFormat(iso = ISO.DATE_TIME) private Date date;
Date date = new Date();
BasicDBObject date= new BasicDBObject("date", date);
Data.insert(date);

How to calculate the difference between two java.sql.Time values?

i have table like below,
id | Lunch_Out | After_Lunch_In
01 | 01:15:00 | 02:00:01
I am trying to find time difference using below code,
while(rst.next())
{
PrintWriter obj1 = response.getWriter();
obj1.println("while entered");
Time a =rst.getTime("Lunch_Out");
Time b =rst.getTime("After_Lunch_In");
PrintWriter objt1 = response.getWriter();
objt1.println("LougOut Time is :"+b);
PrintWriter objt2 = response.getWriter();
objt2.println("LogIn Time is :"+a);
//long c = b.getTime() - a.getTime()
long c = b.getTime() - a.getTime() / (24 * 60 * 60 * 1000);
//PrintWriter objtr = response.getWriter();
//objtr.println("different is :"+c);
Time diff = new Time(c);
PrintWriter objt = response.getWriter();
objt.println("different is :"+diff);
}
Output is:
while entered
LougOut Time is :02:00:02
LogIn Time is :01:15:01
different is :02:00:02
But expecting output is : 00:45:01.where i am doing mistake?
You are converting both a and b to milliseconds (since epoch) then getting the difference. Since your subsequent line involves invoking the Time constructor, you don't need to scale the time to days by dividing with 24 * 60 * 60 * 1000 as you have done. Take the c value only as a difference in milliseconds, then convert it into the Time object diff in the next line.
Your updated code should look like this.
long c = b.getTime() - a.getTime();
Time diff = new Time(c);
However, this will give you a Time object with the correct number of hours, minutes and seconds but whose date will be January 1, 1970. As you have added the MySQL tag to your question, I would suggest you consider Paul's suggestion in his comment.
I suggest you let MySQL do the math for you as part of your query, something like SELECT Lunch_Out, After_Lunch_In, subtime(After_Lunch_In, Lunch_Out) as Lunch_Duration FROM .... See the MySQL reference manual for details.

how to parse and change values in sqlite

I have sqlite db(around 10k entries) with time stored in following format: hh:mmam/pm for example 12:40pm, 6:50am and I need it in milliseconds so they can be compared. Is there a way to make it happen? I am working with Java.
EDIT: Sorry, my question is ambiguous. I want to take value, transform it to milliseconds and overwrite it back, so all values will be stored in milliseconds rather than current format.
Problem was solved with the following python code, post it just in case anyone else will need to do something similar. After prog is done had to manually change type of the column from TEXT to NUMERIC
import sqlite3
from datetime import datetime
def unix_time(dt):
"""Takes datetime object and returns its unix time since epoch"""
epoch = datetime.utcfromtimestamp(0) #January 1st 1970
delta = dt - epoch
return delta.total_seconds()
def unix_time_millis(dt):
return unix_time(dt) * 1000 #milliseconds
db = sqlite3.connect("your_db.sqlite")#connect to initial database
cursor = db.cursor()
cursor.execute("select * from fancy_table")
all_entries = cursor.fetchall() #get our stuff
#new database. Make a copy of initial to prevent serious damage
db_new = sqlite3.connect("your_db_new.sqlite")
for entry in all_entries:
entry = str(entry[0].strip())#cursor returns tuple
#since it is time not a date, get milliseconds of the epoch
date_object = datetime.strptime("Jan 1 1970 " + entry, '%b %d %Y %I:%M%p')
new_time = unix_time_millis(date_object)
#print(entry + " to " + str(new_time))
cursor_update = db_new.cursor()#new cursor
try:
#updating
cursor_update.execute("UPDATE fancy_table SET time = '" + str(new_time) + "' WHERE arr_time = '" + entry + "'")
except Exception as error:
print(error)
db_new.commit()#needs to be commited to take affect
print("done")

Retrieving statistic data in hibernate

I've got a table File for which I created a hibernate entity with fields:
archiveDate: Date,
createDate: Date,
copyDdate: Date,
modifiedDate: Date,
fileSourceId: Long,
fileSize: Long
I have to create a DAO for retrieving statistic data like how many files were archived in a given period of time in given intervals (daily, weekly, monthly, annually) for specified fileSourceId. Like if dao receives arguments like this:
fileSourceId = 1, startDay = '2012/01/01', endDate = '2012/02/01', interval = 'weekly'
it should return some objects like this:
{fileSourceId = 1, endDate = (end date of the first week), fileCount = 100, sizeSum = 10000 }
{fileSourceId = 1, endDate = (end date of the second week), fileCount = 120, sizeSum = 30000 }
and so on. I would like to avoid doing calculations like counting and summing on the java side as there's a couple of hundred of thousands files.
Is it possible to create a query or criteria to do this in Hibernate or it's better to do some view in database (Oracle) and query this view. I would like to avoid any oracle specific function in query because we don't want to be bound to one database (especially that we use h2 as our testing database in integration testss). How would you resolve this problem?

Difference between two times always returns 2 or bigger

I have 2 events in my application. I need the time difference between the two of them so I store the time in a sharedpreferences using this line of code :
public static void PutStatus(Context ctx,boolean stat)
{
if (ctx != null)
{
SharedPreferences shr = ctx.getSharedPreferences("test", Context.MODE_WORLD_READABLE);
shr.edit().putBoolean("SHIFT", stat).commit();
if (stat) shr.edit().putLong("START_TIME", System.currentTimeMillis()).commit();
}
}
And then I calculate the difference between the two date and times using this :
SharedPreferences shr = getApplicationContext().getSharedPreferences("test", Context.MODE_WORLD_READABLE);
long time_stamp = System.currentTimeMillis() - shr.getLong("START_TIME", 0);
Date data = new Date(time_stamp);
The minutes are working great but the hours are 2 hour ahead.
Why is that does it have any connection with timezones ?
The proper way to get a duration with Java is a little bit complicated. You would create it the following way:
import javax.xml.datatype.Duration;
import javax.xml.datatype.DatatypeFactory
...
Duration d = DatatypeFactory.newInstance().newDuration(time_stamp);
System.out.println(d.getHours() + "h:" + d.getMinutes() + "m: " + d.getSeconds() + "s");
For documentation see Duration and DatatypeFactory.
If you need time interval, what about just doing some modulo computations? An hour is 3600 * 1000 milliseconds, day is 86400 * 1000. When you create date this way, you are creating date object relative to 1.1.1970 UTC - this may be as well 2 hours off from timezone where your phone thinks to be.
I would suggest to use two date objects, something like
int diffInDays = (newerDate.getTime() - olderDate.getTime()) / (1000 * 60 * 60 * 24)

Categories

Resources