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');
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'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)
I have list of timezones; and for each timezone, I have to start schedule job. Following is the code
cronexpr = 0 30 8,12,15,17 * * ?
if(cronexpr != null){
for(int i=0;i<tList.size();i++) {
job = new JobDetailImpl("runSMSJob"+i,"SMSJobgrp"+i,SMSJob.class);
trigger = new CronTriggerImpl("runMeJobTesting"+i, "group", "runSMSJob"+i, "SMSJobgrp"+i, cronexpr, tList.get(i));
logger.info("TIMEZONE is "+trigger.getTimeZone());
schd.start();
schd.scheduleJob(job, trigger);
}
Here tList is a list containing several timezones. On my local system its running properly but on server where the timezone is BST, even though the locale is India timezone, it's firing at the BST time.
Do any one have any idea on why its failing to take the specified timezone properly?
Problem. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method Server.getCurrentTime() is not available since it was added only in server version 9.0.
Motivation. My application needs to use views at specific dates. So if there's some difference in system time between client (where the app is running) and server then obtained views are not accurate. In the worst case the client's requested date is in the future for server so the operation results in exception.
After some investigation I haven't found any cleaner solution than using a temporary item. My app requests the item's time of creation and compares it with local time. Here's the method I use to get server time:
public Date getCurrentServerTime() {
Folder rootFolder = project.getDefaultView().getRootFolder();
Topic newItem = (Topic) Item.createItem(project.getTypeNames().TOPIC, rootFolder);
newItem.update();
newItem.remove();
newItem.update();
return newItem.getCreatedTime().createDate();
}
If your StarTeam server is on a Windows box and your code will be executing on a Windows box, you could shell out and execute the NET time command to fetch the time on that machine and then compare it to the local time.
net time \\my_starteam_server_machine_name
which should return:
"Current time at \\my_starteam_server_machine_name is 10/28/2008 2:19 PM"
"The command completed successfully."
We needed to come up with a way of finding the server time for use with CodeCollab. Here is a (longish) C# code sample of how to do it without creating a temporary file. Resolution is 1 second.
static void Main(string[] args)
{
// ServerTime replacement for pre-2006 StarTeam servers.
// Picks a date in the future.
// Gets a view, sets the configuration to the date, and tries to get a property from the root folder.
// If it cannot retrieve the property, the date is too far in the future. Roll back the date to an earlier time.
DateTime StartTime = DateTime.Now;
Server s = new Server("serverAddress", 49201);
s.LogOn("User", "Password");
// Getting a view - doesn't matter which, as long as it is not deleted.
Project p = s.Projects[0];
View v = p.AccessibleViews[0]; // AccessibleViews saves checking permissions.
// Timestep to use when searching. One hour is fairly quick for resolution.
TimeSpan deltaTime = new TimeSpan(1, 0, 0);
deltaTime = new TimeSpan(24 * 365, 0, 0);
// Invalid calls return faster - start a ways in the future.
TimeSpan offset = new TimeSpan(24, 0, 0);
// Times before the view was created are invalid.
DateTime minTime = v.CreatedTime;
DateTime localTime = DateTime.Now;
if (localTime < minTime)
{
System.Console.WriteLine("Current time is older than view creation time: " + minTime);
// If the dates are so dissimilar that the current date is before the creation date,
// it is probably a good idea to use a bigger delta.
deltaTime = new TimeSpan(24 * 365, 0, 0);
// Set the offset to the minimum time and work up from there.
offset = minTime - localTime;
}
// Storage for calculated date.
DateTime testTime;
// Larger divisors converge quicker, but might take longer depending on offset.
const float stepDivisor = 10.0f;
bool foundValid = false;
while (true)
{
localTime = DateTime.Now;
testTime = localTime.Add(offset);
ViewConfiguration vc = ViewConfiguration.CreateFromTime(testTime);
View tempView = new View(v, vc);
System.Console.Write("Testing " + testTime + " (Offset " + (int)offset.TotalSeconds + ") (Delta " + deltaTime.TotalSeconds + "): ");
// Unfortunately, there is no isValid operation. Attempting to
// read a property from an invalid date configuration will
// throw an exception.
// An alternate to this would be proferred.
bool valid = true;
try
{
string testname = tempView.RootFolder.Name;
}
catch (ServerException)
{
System.Console.WriteLine(" InValid");
valid = false;
}
if (valid)
{
System.Console.WriteLine(" Valid");
// If the last check was invalid, the current check is valid, and
// If the change is this small, the time is very close to the server time.
if (foundValid == false && deltaTime.TotalSeconds <= 1)
{
break;
}
foundValid = true;
offset = offset.Add(deltaTime);
}
else
{
offset = offset.Subtract(deltaTime);
// Once a valid time is found, start reducing the timestep.
if (foundValid)
{
foundValid = false;
deltaTime = new TimeSpan(0,0,Math.Max((int)(deltaTime.TotalSeconds / stepDivisor), 1));
}
}
}
System.Console.WriteLine("Run time: " + (DateTime.Now - StartTime).TotalSeconds + " seconds.");
System.Console.WriteLine("The local time is " + localTime);
System.Console.WriteLine("The server time is " + testTime);
System.Console.WriteLine("The server time is offset from the local time by " + offset.TotalSeconds + " seconds.");
}
Output:
Testing 4/9/2009 3:05:40 PM (Offset 86400) (Delta 31536000): InValid
Testing 4/9/2008 3:05:40 PM (Offset -31449600) (Delta 31536000): Valid
...
Testing 4/8/2009 10:05:41 PM (Offset 25200) (Delta 3): InValid
Testing 4/8/2009 10:05:38 PM (Offset 25197) (Delta 1): Valid
Run time: 9.0933426 seconds.
The local time is 4/8/2009 3:05:41 PM
The server time is 4/8/2009 10:05:38 PM
The server time is offset from the local time by 25197 seconds.
<stab_in_the_dark>
I'm not familiar with that SDK but from looking at the API if the server is in a known timezone why not create and an OLEDate object whose date is going to be the client's time rolled appropriately according to the server's timezone?
</stab_in_the_dark>