Parse string description of timezone - java

I get information about timezone in such string format.
(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius
Is it somehow possible to parse it into some TimeZone object in Java with standard library or external one?

Depending how you want to use the TimeZone afterwards you might either create a custom one
String input = "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius";
// assuming the format is always fixed at the beginning
String timeZoneOffset = input.substring(4,10);
TimeZone timeZone = TimeZone.getTimeZone("GMT" + timeZoneOffset);
System.out.println("timeZone = " + timeZone);
output (line wrapped)
timeZone = sun.util.calendar.ZoneInfo[id="GMT+02:00",offset=7200000,dstSavings=0,\
useDaylight=false,transitions=0,lastRule=null]
You might get into trouble related to the daytime savings.
Or you create a lookup map with an entry for each offset (stripped down code snipped)
String input = "(UTC+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius";
// assuming the format is always fixed at the beginning
String timeZoneOffset = input.substring(4,10);
// needs to be initialized somewhere
Map<String, TimeZone> timeZones = new HashMap<>();
// you need to add all offsets
timeZones.put("+02:00", TimeZone.getTimeZone("EET"));
System.out.println("timeZone lookup = " + timeZones.get(timeZoneOffset));
output (line wrapped)
timeZone lookup = sun.util.calendar.ZoneInfo[id="EET",offset=7200000,dstSavings=3600000,\
useDaylight=true,transitions=123,lastRule=java.util.SimpleTimeZone[id=EET,offset=7200000,\
dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,\
startDay=-,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,\
endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]]

Related

How to set on a json a DateTime value with a specific format

I'm setting values on a json that i want to send, but the value DateTime("2019-07-01T03:18:46Z") is not set on the json as i wanted to
I have tried to use the SimpleDateFormat, also with the DateTimeFormatter of the library joda but no one give me the result as a simple DateTime
EventDTO eventDTO = new EventDTO();
eventDTO
.withDescription("Description")
.withIssueType("Notificación CNS")
.withPriority("Medium")
.withProjectKey("10000")
.withIssueSubType("Apoderamiento de aeronave")
.withSummary("Summary")
.withRegion("LECM")
.withAirport("LEBB")
.withRaised(new DateTime("2019-07-01T03:18:46Z"));
when(jiraService.create(eventDTO)).thenReturn(successResponseDTO);
String json = new ObjectMapper().writeValueAsString(eventDTO);
the actual result that I'm getting is :
{"monthOfYear":7,"minuteOfHour":18,"hourOfDay":5,"yearOfEra":2019,"weekyear":2019,"centuryOfEra":20,"yearOfCentury":19,"millisOfDay":19126000,"secondOfDay":19126,"minuteOfDay":318,"era":1,"dayOfMonth":1,"dayOfWeek":1,"dayOfYear":182,"year":2019,"secondOfMinute":46,"millisOfSecond":0,"weekOfWeekyear":27,"zone":{"fixed":false,"uncachedZone":{"cachable":true,"fixed":false,"id":"Europe/Paris"},"id":"Europe/Paris"},"millis":1561951126000,"chronology":{"zone":{"fixed":false,"uncachedZone":{"cachable":true,"fixed":false,"id":"Europe/Paris"},"id":"Europe/Paris"}},"afterNow":false,"beforeNow":true,"equalNow":false}
I expect to get just
2019-07-01T05:18:46.000+02:00

play framework : Pass date to view

I need to pass the date parameter to view in play framework
My controller looks like
something.render(new Date());
And on my view what I've done is
#(myDate : Date)
<script lang="text/javascript">
var time = "#(myDate)";
</script>>
This time variable I further need to use in jQuery.
Thing is Play framework is converting the date to string object.
What I want is date object itself.
If I remove the quotes around "#(myDate)" Java script gives following output.
var backupTimeString = 2015-01-15 00:01:28.767;
Uncaught Syntax Error : expecte number
I really need the object to passed as Date object not as String represnetation of Date
1) If you work in local time, you could pass the time as a formatted string :
something.render( ... new java.text.SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new java.util.Date()) ...)
and convert it to javascript date in the view :
<script>
var t = new Date("#mydate");
</script>
According to http://dygraphs.com/date-formats.html the format aaaa/mm/jj hh:mm:ss is the most robust.
2) In case you don't work in local time, recent browsers accept ISO-8601 date with offset from UTC, for example :
new Date('2015-01-22T12:00-0600')
3) As a last resort, you can pass a timestamp :
something.render(... new java.util.Date().getTime() ...)
<script>
var t = new Date(#mydate);
</script>

Android Localization query

I have been working on localisation for my app and cant seem to find any information about how to handle decimal values and dates from different locals to store in sqllite.
for example:
German decimal 123,53
Uk decimal 123.53
So how do you convert from an edittext field to a valid decimal. At the moment I have my code outputting to a textview rather than sql just for testing. The below code works great when using UK decimal but if I use the german decimal it fails!!
Configuration sysConfig = getResources().getConfiguration();
Locale curLocale = sysConfig.locale;
NumberFormat nf = NumberFormat.getInstance(curLocale);
String convertedString = nf.format(Double.parseDouble(EditTextField.getText().toString()));
TextView showLocalisedNumeric;
showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
showLocalisedNumeric.setText(convertedString);
I have not started with dates yet but I am assuming converting dates for is more straight forward.
After some time working on this I found the solution for localisation, taking a value from input and parsing it to a format that can be understood by SQLlite - For this exercise and to reduce code I have just set it to output to a text view.
// set initial value to variables
String convertedString = "";
double parsedValue = 0.0;
//get value from text field
EditText EditTextField =(EditText)findViewById(R.id.TestNumericValueEntered);
String valueFromInput = EditTextField.getText().toString();
//Get current Locale from system
Configuration sysConfig = getResources().getConfiguration();
Locale curLocale = sysConfig.locale;
//Set number formats
NumberFormat nf_in = NumberFormat.getNumberInstance(curLocale);
NumberFormat nf_out = NumberFormat.getNumberInstance(Locale.UK);
//try to parse value, otherwise return error message
try {
parsedValue = nf_in.parse(valueFromInput).doubleValue();
// use nf_out.setMaximumFractionDigits(3) to set max number of digits allowed after decimal;
convertedString = nf_out.format(parsedValue);
}catch(ParseException e){
convertedString = "Unable to translate value";
}
//Output result
TextView showLocalisedNumeric;
showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
showLocalisedNumeric.setText(convertedString);
As I was adding this answer I realised that a nice addition to the code would be to check if the current locale is the same as the one you plan to parse to, if so then the conversion(parsing) can be skipped.

SQL "missing in or out parameter at index"

i have this code for create query and execute sql-procedure but i catch missing-exception
public String generateQuery(Integer idAccount, Long[] phoneList, Date date){
StringBuilder query=new StringBuilder();
query.append("declare arr_pn owa_util.vc_arr;\n");
query.append("begin\n");
int idx = 1;
for (Long p : phoneList)
{ query.append("arr_pn(" + idx + "):='" + String.valueOf(p) + "';\n"); idx++; }
query.append("call LOC_MAINCLIENT.set_client_relations(");
query.append("id_account_ => " + idAccount);
query.append(", phone_number_list_ => arr_pn");
query.append(", dt_ => " + date);
query.append("); end;");
return String.valueOf(query);
}
after that i get this query
declare arr_pn owa_util.vc_arr;
begin
arr_pn(1):='12345';
arr_pn(2):='678970';
arr_pn(3):='5675675';
call LOC_MAINCLIENT.set_client_relations(id_account_ => 123, phone_number_list_ => arr_pn, dt_ => Sun Mar 24 21:54:00 NOVT 2013); end;
what i did wrong?
At the moment the date string isn't quoted, so it's in valid anyway, but the colons will be interpreted by the parser as bind variable markers; specifically it'll be looking for bind variables :54 and :00.
The quick answer is to put the date string into quotes. But that date format is unlikely to match what your database (session) is expecting, so you'd need to format the date into a string it can use and provide the format as well to avoid ambiguity.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
query.append(", dt_ => to_date('" + sdf.format(date)
+ "', 'YYYY-MM-DD HH24:MI:SS')");
You also don't need the call, so get rid of that. That would produce a string like this (with added line breaks and indentation to make it a little easier to see):
declare
arr_pn owa_util.vc_arr;
begin
arr_pn(1):='12345';
arr_pn(2):='678970';
arr_pn(3):='5675675';
LOC_MAINCLIENT.set_client_relations(id_account_ => 123,
phone_number_list_ => arr_pn,
dt_ => to_date('2013-03-24 21:54:00', 'YYYY-MM-DD HH24:MI:SS'));
end;
Assuming your package procedure is declared as:
procedure set_client_relations(id_account_ number,
phone_number_list_ owa_util.vc_arr, dt_ date);
... this this should run. Whether it does what you actually want is a different matter, of course.
You may also need to do something with the time zone if the database doesn't match your locale.
The proper way to do it is to use a prepared statement, provide all the values as bind variables, and pass the correct data types - passing the date as a date rather than as a string representation. That's a little more complicated for an array but certainly do-able. You've said this is legacy code and you have to use this, but you should still investigate switching to bind variables.

File fully populating

I have this piece of code that is supposed to insert data in a table and fill a txt file with the same data. However I am finding that the table is being filled with the appropriate 2019 rows but the file only contains 1639 with a [Incomplete last line] message at the bottom. What is causing this?
while(ora_rs.next()){
sql_stmt.executeUpdate("INSERT INTO SCHED_BUNDLES_TEMP_TEST VALUES (" +
ora_rs.getString("BUNDLE")+", " +
ora_rs.getString("DROPPER_ID")+", '" +
ora_rs.getString("SCHED_DT")+"')");
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date new_date = (Date)formatter.parse(ora_rs.getString("SCHED_DT"));
SimpleDateFormat newFormat = new SimpleDateFormat("MM/dd/yyyy");
String final_string = newFormat.format(new_date);
out.write(ora_rs.getString("BUNDLE")+"|"+ora_rs.getString("DROPPER_ID")+"|"+final_string+"\n");
ii++;
}
My guess is you have a buffered stream and you are not close()ing or flush()ing the stream which means the end of the file is not being written (as its still in memory)

Categories