Having country-state code as input, is it possible to get the timezone using Java?
For example us-tx -> (GMT-6)
Tried using this answer, however this method uses only the country code, without the state and the output is :
US/Alaska_US/Aleutian_US/Arizona_US/Central_US/East-Indiana_US/Eastern_US/Hawaii_US/Indiana-Starke_US/Michigan_US/Mountain_US/Pacific_US/Pacific-New_US/Samoa
This isn't possible - in any language. Many US states have more than one time zone, depending on which part of the state you are referring to:
From Wikipedia:
You can clearly see on this map, many states where the time zone boundary does not follow the state boundary.
Related
I need to store the current time as a String in a database. The time can be in different timezones, so I'm looking at using Java SE 8's new ZonedDateTime class.
I notice that the toString() method automatically outputs:
2016-04-15T17:40:49.305-05:00[America/Chicago]
This also seems to be readable by ZonedDateTime.parse() and convert to the right values.
If all I am doing is storing these values and I don't need to ever convert the value to a user-readable format, is this all I need to do to accurately store data with proper timezones? For example, if I insert two ZonedDateTimes into an SQL database by storing their toString() representations, and I later read in these times by using ZonedDateTime.parse(), can I expect things like isAfter() and isBefore() to work just fine?
Or am I missing a step in between? After trying to figure out timezones in Java 7 this feels almost too easy.
Generally speaking I would avoid relying on parsing the toString() representation of any class in my application.
toString() is meant to provide a human readable version of a class so it's subject to change from relase to release.
I would suggest you to force the format to be the one that you expect, e.g applying:
String toStoreInDb = DateTimeFormatter.ISO_ZONED_DATE_TIME.format(zonedDateTime);
...
ZonedDateTime fromDb =
ZonedDateTime.parse(stringFromDb, DateTimeFormatter.ISO_ZONED_DATE_TIME);
This way your application will resist to any toString() change.
Moreover take a look at this bug:
Bug in ZonedDateTime.parse()
Yes, that will accurately store the date, and using the .parse() method will allow you to use the other methods of ZoneDateTime. Though if you want to be able to use sorting functions with your db then you will need to either manually convert the ZonedDateTime into a timestamp or use your ORM's features to do it for you.
Hy,
Lets say you have Varchar-Database values in a column that are cAmeLCaSe and you always want to display them UPPERCASE in a view.
Is it now better to select those entrys using the (for example) UPPER-Function of Oracle
or to loop the results and call the .toUpperCase() Method from within the Java Code after the selection has been made?
I know its a bit of a general question and i will of corse comment after having made performance messurments of the above two possibilitys. But i am more after a good source of information that addresses such questions in general (like for example "is it better do run sorting db- side or in programm-code?" and questions like this for common Solutions like .Net/Java and Oracle/ MSSQL Server.
Many thanks you took the time to read this questions, i appreciate any input and wish you a great day.
Regards
Jan
It depends on where and how the uppercased value is used.
If this is only used in the frontend (I assume with "view" you did not mean a database view) then I'd go for a toUpperCase() ideally using the user's locale.
If you are using the uppercase value for comparison I'd use the Oracle function to ensure that the you have a consistent behaviour. I'm think of e.g. a condition where you compare the column value to a string constant: WHERE upper(foobar) = upper('SomeValue') If you used Java's toUpperCase() that might apply different (locale dependent) rules than Oracle would use.
I believe always my code should be database independent.
String upper = string.toUpperCase();
Because,it's database independent.If I shift my database to some other,I need not to change my code.
In a nutshell your specific requirements should take in to consideration.
Our database keeps track of a number of "Production Facilities". Each facility has an address, name, and most importantly timezone. How do I figure out the name of a timezone?
It was obvious for our initial facilities because the code is named after our city (America/Edmonton). How can I more generally determine the correct timezone code to use in Java via the call DateTimeZone.forID("timeZone") ex DateTimeZone.forID("America/Edmonton")?
Specifically we are opening a facility in Atlanta Georgia and I am unsure which code to use? Is it one of these?
"Atlantic/South_Georgia"
US/Eastern"
"EST5EDT"
"EST"
This kind of information can be really tricky (not to mention tricky to keep current). It can actually vary county by county (there is an excellent West Wing scene about this :). Google Maps API recently included support to go from lat+lon to TimeZone
The IANA standard timezone identifier for Eastern Time is America/New_York. Presumably this is the standard Joda time is using, since (1) everyone uses it and (2) the city-name-as-identifier gives it away.
You can get a list with:
for (String string : TimeZone.getAvailableIDs(TimeZone.getTimeZone(
"GMT-05:00").getRawOffset())) {
System.out.println(string);
}
And it will include (among many others) "US/Eastern".
You can list the available timezone id's using this method:
http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getAvailableIDs()
The time zone data seems to come from this database:
http://en.wikipedia.org/wiki/Tz_database
You can do lookups in it here:
http://twiki.org/cgi-bin/xtra/tzdatepick.html
I've been trying to isolate a bug in my application. I succeeded in producing the following "riddle":
SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat f2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date d = f1.parse("2012-01-01T00:00:00+0700");
String s1 = f1.format(d); // 2011-12-31T18:00:00+0700
String s2 = f2.format(d); // 2011-12-31T18:00:00+0100
I get the values in comments when I run this code on Android API 7 (yes, really). This behavior depends on particular Java implementation.
My questions are:
Why s1 does not equal s2?
And more importantly, why s1 is incorrect? While s2 points to a proper point in time, s1 does not. There seems to be a bug in Android's SimpleDateFormat implementation.
ANSWER TO QUESTION 1: See the answer by BalusC:
[After using SimpleDateFormat#parse] any TimeZone value that has previously been set by a call to setTimeZone may need to be restored for further operations.
ANSWER TO QUESTION 2: See the answer by wrygiel (myself).
This is due to a bug in Android 2.1 (API 7).
This is mentioned in javadoc of DateFormat#parse():
Parse a date/time string according to the given parse position. For example, a time text "07/10/96 4:5 PM, PDT" will be parsed into a Date that is equivalent to Date(837039900000L).
By default, parsing is lenient: If the input is not in the form used by this object's format method but can still be parsed as a date, then the parse succeeds. Clients may insist on strict adherence to the format by calling setLenient(false).
This parsing operation uses the calendar to produce a Date. As a result, the calendar's date-time fields and the TimeZone value may have been overwritten, depending on subclass implementations. Any TimeZone value that has previously been set by a call to setTimeZone may need to be restored for further operations.
Note the last paragraph. It unfortunately doesn't explain when exactly this will occur. To fix your particular problem you need to explicitly set the desired timezone before the formatting operation.
As to the mutability of SimpleDateFormat itself, this is known for years. You should never create and assign an instance of it as a static or class variable, but always as a method (threadlocal) variable.
This is due to a bug in Android 2.1 (API 7). It seems that Android programmers missed some undocumented Java behavior (which is classified as an unfixable bug itself!) in their implementation of Android 2.1.
Your question intrigued me so I went ahead and compiled your code. The result? As expected...
2011-12-31T18:00:00+0100
2011-12-31T18:00:00+0100
The two values are the same, are you using some concurrency? Maybe the variable gets changed on another thread right before the f2.format(d).
I tried to compare s1 and s2 by running the same program. they come equal to me.
I am tasked with creating a small program that can read in the definition of a FSM from input, read some strings from input and determine if those strings are accepted by the FSM based on the definition. I need to write this in either C, C++ or Java. I've scoured the net for ideas on how to get started, but the best I could find was a Wikipedia article on Automata-based programming. The C example provided seems to be using an enumerated list to define the states, that's fine if the states are hard coded in advance. Again, I need to be able to actually read the number of states and the definition of what each state is supposed to do. Any suggestions are appreciated.
UPDATE:
I can make the alphabet small (e.g. { a b }) and adopt other conventions such as the
start state is always state 0. I'm allowed to impose reasonable restrictions on the number of
states, e.g. no more than 10.
Question summary:
How do I implement an FSA?
First, get a list of all the states (N of them), and a list of all the symbols (M of them). Then there are 2 ways to go, interpretation or code-generation:
Interpretation. Make an NxM matrix, where each element of the matrix is filled in with the corresponding destination state number, or -1 if there is none. Then just have an initial state variable and start processing input. If you get to state -1, you fail. If you run out of input symbols without getting to the success state, you fail. Otherwise you succeed.
Code generation. Print out a program in C or your favorite compiler language. It should have an integer state variable initialized to the start state. It should have a for loop over the input characters, containing a switch on the state variable. You should have one case per state, and at each case, have a switch statement on the current character that changes the state variable.
If you want something even faster than 2, and that is sure to get you flunked (!), get rid of the state variable and instead use goto :-) If you flunk, you can comfort yourself in the knowledge that that's what compilers do.
P.S. You could get your F changed to an A if you recognize loops etc. in the state diagram and print out corresponding while and if statements, rather than using goto.
One non-hardcoded way to represent an automaton is as a transition matrix, which allows to represent for each current state, and each input character, what the next state is.
You haven't actually asked a question. You'll get more and better help if you have a specific question for a specific task (but still give the overall goal). The question should be narrow in scope (e.g. not "How can I implement an FSA?").
As for how to represent an FSA (which seems to be what you're having difficulties with), read on.
Start by considering the definition of an FSM: it's an alphabet ∑, a set of states S, a start state s0, a set of accept states A and a transition function δ from a state and a symbol to a state. You have to be able to determine these properties from the input. Any states not reachable by the transition function can be dropped to produce an equivalent FSM. The minimal set of states and alphabet are thus implicit in the transition function; you could make your FSM easier to use (and harder to implement, but not much harder) by not requiring either ∑ or S in the input.
You don't need to use the same representation for states that the input uses. You could use unsigned integers for your internal representation, as long as you have a map from integers to strings and strings to integers so you can convert between the internal representation and external representation. This way, your transition function can be stored as an array, so the transition step can be performed in constant time.
A simpler approach would be to use the external representation as your internal representation. With this option, the transition function would be stored as a map from strings and symbols to strings. The transition step would probably be O(log(|S|+|∑|)), given the performance of most map data structures. If symbols are represented as integers (e.g. chars), the transition function could be represented as a map from strings to an array of strings, giving O(log(|S|)) performance.
Yet another optionmodeled after the graph view of an FSM, is to create a class for states. A state has a name (the external representation). States are responsible for transitions; send a symbol to a state and get back another state.
class State {
property name;
State& transition(Symbol s);
void setTransition(Symbol s, State& to);
}
Store the set of states as a map from names to states.
There you go, three different places to start, each with a different way to represent states.
Stop thinking about everything at once. Do one thing at a time
- come with language of state machine
- come with language for stimulus
- create sample file of one state machine in language
- create sample file of stimulus
- come with class for state
- come with class for transition
- come with class for state machine as set of states and transitions
- add method to handle violation to state class
- code a little parser for language
- code another parser for language
- initial state
- some output thing like WriteLn here and there
- main method
- compile
- run
- debug
- done
The way the OpenFst toolkit does it is: A FSM has a vector of states, each of which has a vector of arcs. Each arc has an input (and output) label, a target state ID and a weight. You could take a look at the code. Maybe it will inspire you.
If you're using an object-oriented language like Java or C++, I'd recommend that you start with objects. Before you worry about file formats and the like, get a good object model for a finite state automata and how it behaves. How will you represent states, transitions, events, etc.? Will your FSA be a Composite? Once you have that sort of thing working you can get the file formats right. Anything will do: XML, text, etc.