Codenameone get time - time

Is there a method in codename one for getting the system's time? Like, what hour it is in the device. Also, I'd like to get the day of the week. Because I want to make a program that constantly runs a clock, and it compares int variables with the current hour, and string variables with the week day. Is there a way to do it? I'm pretty new in programming languages.

System.currentTimeMillis() will return the time. Date, TimeZone and java.util.Calendar are all available just like in standard Java.

Related

Setting time zone offset in java 8 time versus joda time

I work for an organization in two locations. One of them is Chile, where daylight savings time is extremely unpredictable and often varies from year-to-year. We have an application that is dependent on time and up until now, have been using joda time. When the Chilean government decides to change daylight savings, we use joda code to set an offset to the default DateTimeZone:
/**
* Updates the default time zone, i.e. the time zone which is used as local time.
*/
private void updateDefaultTimeZone() {
if (isEmpty(Configuration.Value.TIME_ZONE_OFFSET)) {
// make the site's default time zone the current time zone for joda time,
// this should always be the case for the non-Chile site, and work for the Chile site during most of the year
DateTimeZone.setDefault(siteService.getSiteTimeZone());
} else {
// makes a user defined time zone the current time zone for joda time
// this will be used when Chile is delaying or pulling forward the transition from/to daylight
// saving time and the JVM is therefore not able to calculate the local times appropriately
Integer offset = getInteger(Configuration.Value.TIME_ZONE_OFFSET);
DateTimeZone.setDefault(DateTimeZone.forOffsetHours(offset));
}
}
We're trying to transition our code base from joda time to Java 8 time, but I have really no idea the classes that are involved in doing something similar. I'm guessing perhaps ZoneRules, but I'm not sure. Does anyone have any hints as to how to most cleanly accomplish this?
Additionally, what is the best way of converting units in Java 8 time? Say I have 24 hours and I want to convert it into days. (I ask because in this case, it seems many methods work with milliseconds and I want to work with hours, but think there must be a better built-in way to convert than to do the arithmetic by hand.)
Use java.util.TimeZone.setDefault(TimeZone). Because JSR-310 java.time.* is integrated with the JDK, there is no need for a separate method.
(To convert units, you may find it easiest to use TimeUnit, but perhaps a separate more focussed question would help you there.)
JodaStephen has said it. He’s the lead developer of both Joda-Time and java.time, so definitely the authority here. I add just some supplementary thoughts.
Consider not relying on a default time zone
The default time zone of the JVM can be changed at any time from another part of your program and from other programs running in the same JVM. So relying on it is fragile. java.time (Java 8 time) consistently offers you the possibility of specifying time zone for all time zone sensitive operations. My habit is to use this. So my suggestion is that you store the time zone somewhere in your program where you alone control who’s tampering with it and code your date and time operations to use this stored setting and not the default time zone of the JVM.
If you still rely on the default: The TimeZone class has a bad design flaw. This would look sound to me at first sight:
TimeZone.setDefault(TimeZone.getTimeZone("America/Santiago_de_Chile"));
It isn’t! Look at the output from
System.out.println(TimeZone.getDefault().getID());
GMT
Extremely confusing IMHO. The correct time zone ID is America/Santiago, not America/Santiago_de_Chile. So we should have expected an IllegalArgumentException or similar here. Instead TimeZone just tacitly gives us a completely wrong time zone, GMT.
Instead use:
TimeZone.setDefault(TimeZone.getTimeZone(ZoneId.of("America/Santiago_de_Chile")));
Exception in thread "main" java.time.zone.ZoneRulesException: Unknown time-zone ID: America/Santiago_de_Chile
Time unit conversions
Like JodaStephen I routinely use TimeUnit for time unit conversions, but I try to remember to think twice before doing so.
System.out.println(TimeUnit.HOURS.toDays(24));
System.out.println(TimeUnit.DAYS.toHours(400_000_000_000_000_000L));
1
9223372036854775807
It looks right, doesn’t it? It isn’t either! For two reasons:
A day is not always 24 hours. When Chile goes from standard time to summer time (DST) or vice versa, a day is 23 or 25 hours.
The conversion doesn’t report long overflow. The latter conversion overflows. TimeUnit tacitly gives us the closest value that can fit in a long, in this case the value of Long.MAX_VALUE.
When you know what you are doing and you know your conversions don’t overflow, you may use it. I also do most of my int math without checking for overflow. java.time offers a nice converstion that does check for overflow:
System.out.println(Duration.ofDays(400_000_000_000_000_000L).toHours());
Exception in thread "main" java.lang.ArithmeticException: long overflow
I even find this code a bit more readable than the TimeUnit code.

When the user's timezone is known, can the bot framework handle yesterday/tomorrow correctly?

In some cases, the bot may have knowledge of the user's timezone. Is there a way to pass this knowledge to the bot framework so that it can handle certain date forms correctly - e.g. "tomorrow" & "yesterday"? Even things like "next friday" are sometimes sensitive to the timezone.
Currently, it appears that these are handled assuming the user's timezone offset is zero.
It seems that the chronic parser is unreachable so you can't really change anything to that. I see 3 solutions.
Solution 1: Create your own RecognizeDateTime class to work with utc time or however you want.
Solutions 2: When you get the date (in the validation method for example) add the utc offset to the time. This will preserve the right date, for utc times and local times.
dateTime += TimeZone.CurrentTimeZone.GetUtcOffset(dateTime);
solution 3: When the datetime is created by using a string like "yesterday", the day is correct but the time defaults to 00:00 or 12AM. To make this less sensitive you can just add 12 hours to the UTC time. This will preserve the day in almost all timezones. (All timezones above 12+ will have a problem. Luckily there aren't many people there.) (This is the solution I'm currently using for one of my solutions)

Need to store time field input as local time

I can't figure out how to make user input for a time field local. I'm creating events in a form with a start_time and an end_time. I'd like to bring in a time from a time field, and store the user's input as their local time. I'd then like to convert it to UTC and compare it to Time.now.utc, in order to determine whether or not the event has started or ended.
I thought about converting the start and end times with start_time.localtime, and then adding/subtracting that from start_time (the default for time_field inputs is UTC), and storing that offset as a variable. Then add/subtract that offset from my stored times, and compare to Time.now (which the default is local).
This seems like much more work than is necessary, as I'm sure this is a common function that people need to use. Is there some local_time_field implementation for forms that I haven't been able to find, or any other overlooked simple solutions?
Any input is appreciated. Thanks!
The most direct way to get at the user's locale is in the browser, with JS. new Date(userDateString).getTimeZoneOffset() will return the user's offset in minutes from UTC. You can use that to convert the times to UTC before sending them up to the server. Of course, this won't work if you need to support JS-less users. Those users will need some other approach--you could make a "my time-zone" dropdown, for example.
Whatever approach you take, you'll have far fewer headaches if you only store times in UTC. Convert user-local times to UTC as early as possible in processing, and only convert back to the user's locale when you're about to display it. Otherwise you have to deal with not only time zones but also DST, and it's a huge headache.

Representing local timestamps in Ruby based REST API

Perhaps this question should be broken up into two posts, but I currently have an API for a few business customers. I am currently using ISO 8601 timestamps with a UTC time zone to represent times. However, I don't like the idea of these timestamps being attached to any timezone because the times should be the same no matter what timezone you are in. 5PM UTC should be 5PM CST, etc...
I know that you can leave the Z off of an ISO timestamp, and it will be interpreted as whatever local time you are in. Is this ok practice? And if so, how do I do this in Ruby? I read the doc for the Time class and didn't see anything about this.
EDIT: Let me re-word this just a little bit, or atleast clarify something. The reason why I'm seeking timestamps that aren't attached to a timezone is exactly because I know that my client servers and API server will hardly ever match up. If a client is submitting an event with a time, that time needs to be ambiguously equal to the ambiguous locale specific to the event that the user is working on.
That's a mouthful...assume that I'm working on an event scheduler. Each event belongs to a storefront or location of a company. When times are being shown for a location, it is assumed that the times shown are in the timezone of the location, and for clarity's sake should never be shown at a time formatted to a user's local timezone. If I'm looking at the scheduler on the East Coast, but looking at events for locations on the West Coast, the times I should see should be local to the locations on the West Coast, not adjusted for my timezone.
I know a solution could be to simply store times with timezone information for the location its associated to. But the use case that a user would want to convert a time to their timezone is VERY rare, and I'd rather make implementing my API easier...this was actually my original implementation but implementing the API in many different environments and across multiple programming languages, it became clear that it is a hurdle to show times local to that timestamp's timezone for a lot of languages. If a user wanted to convert times to their local timezone I could easily store global timezone information for the location object itself.
I don't know what you mean by "the times should be the same no matter what timezone you are in. 5PM UTC should be 5PM CST, etc..". 5PM UTC clearly isn't 5PM CST!
Anyway, I don't think that what you are proposing is an ok practice. Suppose you leave off the Z and have a timestamp be interpreted as whatever local time you are in. Since this is a network API, the client and server might not be in the same timezone. When the client submits a "local" time, what does it mean? The local time on the client (if so, how does the server know what that is?)? The local time on the server? It's ambiguous. This is the crux of the reason why just about the only reasonable thing to do is to use UTC throughout.
What you can do is attach a timezone to a timestamp if it might be relevant. For example, "you should observe one minute of silence at 2012-11-10T22:00:00Z in honour of the soldiers who died in WW1" sounds weird because Rememberance Day isn't on November 10! "you should observe one minute of silence at 2012-11-11T11:00:00+13:00" sounds a lot better once you put that New Zealand time zone in there... In this case you can keep and timestamp (in either local or UTC) together with the timezone offset (e.g. store both of them together in your database).
It does, however, depend on what your times represent. For example, in "at equinoxes, sunset happens at 18:00" it makes sense to use an abstract time that isn't qualified with a timezone (it's true in every timezone, and/or you're talking about solar time). But attaching a date to this abstract time makes little sense, so I don't think you would be talking about ISO8601 in this case.

relativity of the timestamp to the time zone

I wonder if, when you call something like that
time();
it returns the timestamp relatively to your time zone setting or to UTC ?
For example, when syncing two agents, that must be important to take care of it, doesn't it ?
You are absolutely right that the time needs to be adjusted for users at different locations.
First, you need to be able to know
what timezone each agent is in, which you cannot really guess, but ask the client to include the info in the request.
Then, depending on the language you
are using, you can either call some
function with the timezone offset as
the parameter to get the adjusted time, or calculate the
time yourself by adding
60*60*1000*offset milliseconds to the
UTC time.
In python e.g. time.time
[r]eturns the time as a floating point number expressed in seconds since the epoch, in UTC.

Resources