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.
Related
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;
I use the code below to fetch the user's calendar events for the current day.
TODAY_MS is a timestamp of the start of the day and ONE_DAY_MS is a day in milliseconds (1000 * 60 * 60 * 24).
However, this code only gets upcoming events. It doesn't return earlier events in the day.
(i.e.: If I run this at 3PM, it won't return an event that happened from 1 to 2 PM because the event is completed.)
How would I go about getting all of the events in a time period, including those who are completed?
Uri.Builder builder = WearableCalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, TODAY_MS);
ContentUris.appendId(builder, TODAY_MS + ONE_DAY_MS - 1);
final Cursor cursor = mContext.getContentResolver().query(builder.build(), null, null, null, null); // Could optimize this line for speed.
Thank you!
In Google Calendar API v3, under Events:list, you can use the parameter timeMin and timeMax for an event's time to filter.
Here's an sample of minimum and maximum time:
timeMin='2012-10-25T00:00:00Z'
timeMax='2012-10-26T00:00:00Z'
You may also get 2 different date like this:
// Start date from where to get the events
$query->setStartMin('2013-01-01');
// End date
$query->setStartMax('2013-03-20');
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")
I'm a Stata user trying to make use of Stata's Java API. I want to use Java to return the time of last modification of a file to Stata. However, I think I'm running into issues with time zones.
Quick background on times in Stata for non-Stata users: Times are represented by the number of milliseconds since January 1, 1960 00:00:00.000. Stata does not have time zones, so I want the return value from the Java function to be the number of milliseconds since midnight on January 1, 1960 in my time zone (America/New York).
Here is my attempt at the Java function (I can post it in its entirety if that would be helpful):
import com.stata.sfi.*;
// Other imports
public class SFileAttribs
{
// Syntax: lastModified(String filename, String scalar_name)
// Stores in the Stata scalar scalar_name the time of last
// modification of filename.
public static int lastModified(String[] args)
{
// Code here...
// Get the time.
FileTime time;
try {
time = (FileTime) Files.getAttribute(path, "lastModifiedTime");
}
catch (IOException e) {
SFIToolkit.errorln("file I/O error on read");
return(692);
/*NOTREACHED*/
}
// Store the time in the scalar.
Calendar cal1960 = Calendar.getInstance();
cal1960.set(1960, 0, 1, 0, 0, 0);
cal1960.set(Calendar.MILLISECOND, 0);
Scalar.setValue(args[1], time.toMillis() - cal1960.getTimeInMillis());
return(0);
}
}
Back in Stata, I run this command:
// Calls SFileAttribs.lastModified("Test.txt", "filetime").
javacall SFileAttribs lastModified, args("Test.txt" "filetime")
However, the result is an hour earlier than it should be:
. display %tc filetime
24oct2013 12:54:36
The time of last modification in my time zone is 13:54, not 12:54.
I am really struggling on this one and would appreciate any suggestions.
EDIT:
Perhaps predictably given that I'm coming from a language with no time zones, I think I messed up daylight savings. In my time zone, it is now DST, but in the same time zone in January 1, 1960, it was not DST. I need to account for that:
// Store the time in the scalar.
Calendar now = Calendar.getInstance();
Calendar cal1960 = Calendar.getInstance();
cal1960.set(1960, 0, 1, 0, 0, 0);
cal1960.set(Calendar.MILLISECOND, 0);
int dstHour = (cal1960.getTimeZone().inDaylightTime(cal1960.getTime()) ? 1 : 0) -
(now.getTimeZone().inDaylightTime(now.getTime()) ? 1 : 0);
cal1960.set(Calendar.HOUR, dstHour);
Scalar.setValue(args[1], time.toMillis() - cal1960.getTimeInMillis());
Is there an easier way to do this?
The community-contributed command filesys is the easiest way to do exactly what you want:
. findfile auto.dta
. filesys `r(fn)', attributes
. return list
macros:
(some output omitted)
r(accessednum) : "1871843910000"
r(modifiednum) : "1745362526000"
r(creatednum) : "1745362526000"
r(accessed) : "25apr2019 20:38:30"
r(modified) : "22apr2015 22:55:26"
r(created) : "22apr2015 22:55:26"
. display %tcHH:MM `r(modifiednum)'
22:55
You can install the filesys command by using the
community-contributed command github:
. net install github, from("https://haghish.github.io/github/")
. github install wbuchanan/StataFileSystem
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)