setting a format for a date in ms access - java

I'm trying to format a date formatted result from a database into date only. ("dd"). The query results are formatted like this, 2014-05-17 00:00:00 I want to extract only "17", How can I achieved this? This is my code.
String query = "SELECT DISTINCT date FROM Attendance;";
Object[][] queryResult = connectToDB(headerQuery);
for(int x = 0; x < queryResult.length; x++){
for(int y=0; y < queryResult[x].length; y++){
Object temp = queryResult[x][y];
SimpleDateFormat format = new SimpleDateFormat("dd");
System.out.print(format.format(temp));
System.out.println(temp+ "<-----");
}
System.out.println("---");
}
this is my error
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Date
UPDATE: I've changed the for-loop into this:
for(int x = 0; x < queryResult.length; x++){
for(int y=0; y < queryResult[x].length; y++){
String temp = (queryResult[x][y]).toString();
SimpleDateFormat format = new SimpleDateFormat("dd");
Date date = (Date) format.parse(temp);
System.out.println(date+ "<-----");
}
System.out.println("---");
}
but it still does not format the date;

OK so you're trying to format a String. That is, temp is a String and you can't pass that into format. You need to turn that String into a Date then pass it into format. Here's how.
But, even better, you should be returning a Date from the query instead of a String. That'll make your life much easier. Then you don't need to change any other part of the code.
Show us your connectToDB. Assuming it's using JDBC, you should get the result by calling ResultSet.getDate

Why not use SQL to extract the day part?
SELECT DatePart('d', [date]) as theDay FROM Attendance

Related

Insert DateTime into BigQuery in Stream

I am trying to insert data into a datetime field in BigQuery via WriteStream in Java and keep getting the error
java.util.concurrent.ExecutionException: io.grpc.StatusRuntimeException: INVALID_ARGUMENT: Cannot return an invalid datetime value of 1639484762470 microseconds relative to the Unix epoch. The range of valid datetime values is [0001-01-01 00:00:00, 9999-12-31 23:59:59.999999] on field date_time.
I tried different options: seconds, milliseconds, microseconds, cast from Unix format to Microsoft, insert formatted string (then I get an error that it should be INT64).
Where am I going wrong?
Code is pretty simple
try (JsonStreamWriter writer = JsonStreamWriter.newBuilder(writeStream.getName(), writeStream.getTableSchema(), client).build()) {
for (int i = 0; i < 2; i++) {
JSONArray jsonArr = new JSONArray();
for (int j = 0; j < 10; j++) {
JSONObject record = new JSONObject();
Date date = new Date();
record.put("date_hash", date.hashCode());
record.put("date_string", date.toString());
record.put("date_time", date.getTime());
jsonArr.put(record);
}
ApiFuture<AppendRowsResponse> future = writer.append(jsonArr, i * 10);
AppendRowsResponse response = future.get();
}
}

java: how to get Timezone abbreviation (from offset)?

My code like belows, I am using android. I found different devices may have different result.
Using different phone: I can get : "EST" or "GMT-05:00".
However, I just want to get abbreviation(just like "EST").
How can I get the abbreviation (or change offset to abbreviation)?
String timezone =Calendar.getInstance().getTimeZone().getDisplayName(false, TimeZone.SHORT);
If anyone else need the solution : I just tweak the code and get desired short name, which i needed to display to user.
private static String getTimeZoneShortName() {
String tz = TimeZone.getDefault().getDisplayName();
String[] stz = tz.split(" ");
StringBuilder sName = new StringBuilder();
for (int i = 0; i < stz.length; i++) {
sName.append(stz[i].charAt(0));
}
return sName.toString();
}

Java.Lang.Double[] to Double[] issue for Polynomial from CSV

First of all thanks for your help in advance.
I'm writing an investment algorithm and am currently pre-processing CSV historical data. The end goal for this part of the process is to create a symmetrical co-variance matrix of 2k x 2k / 2 (2 million) entries.
The Java class I'm writing takes a folder of CSVs each with 8 bits of information, key ones being Date, Time & Opening stock price. Date & time have been combined into one 'seconds from delta' time measure and opening stock prices remain unchanged. The output CSV contains the above two pieces of information also with a filename index for later referencing.
In order to create the co-variance matrix each stock on the NYSE must have a price value for every time, if values are missing the matrix cannot be properly completed. Due to discrepancies between time entries in the historical training CSV, I have to use a polynomial function to estimate missed values, which then can be fed into the next process in the chain.
My problem sounds fairly simple and should be easy to overcome (I'm probably being a massive idiot). The polynomial package I'm using takes in two arrays of doubles (Double[] x, Double[] y). X pertaining to an array of the 'seconds past delta' time values of a particular stock and Y the corresponding price. When I try to feed these in I'm getting a type error as what I'm actually trying to input are 'java.lang.Double' objects. Can anyone help me with converting an array of the latter to an array of the former?
I realise there is a load of ridiculousness after the main print statement, these are just me tinkering trying to miraculously change the type.
Again thanks for your time, I look forward to your replies!
Please find the relevant method below:
public void main(String filePath) throws IOException {
String index = filePath;
index = index.replace("/Users/louislimon/Desktop/Invest Algorithm/Data/Samples US Stock Data/data-1/5 min/us/nyse stocks/1/", "");
index = index.replace(".us.txt", "");
File fout = new File("/Users/louislimon/Desktop/Invest Algorithm/Data.csv");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
Reader in = new FileReader(filePath);
Iterable<CSVRecord> records;
try {
records = CSVFormat.EXCEL.withSkipHeaderRecord(true).parse(in);
} catch ( IOException ex ) {
System.out.println ( "[ERROR] " + ex );
return;
}
ZoneId zoneId = ZoneId.of("America/New_York");
boolean tmp = true;
Instant firstInstant = null; // Track the baseline against which we calculate the increasing time
ArrayList<Double> timeVals = new ArrayList<Double>();
ArrayList<Double> priceVals = new ArrayList<Double>();
for ( CSVRecord record : records ) {
if(tmp){
tmp = false;
}
else {
//System.out.println(record.toString());
String dateInput = record.get(0);
String timeInput = record.get(1);
Double price = Double.parseDouble(record.get(2));
LocalDate date = LocalDate.parse(dateInput);
LocalTime time = LocalTime.parse(timeInput);
//Double price = Double.parseDouble(priceInput);
LocalDateTime ldt = LocalDateTime.of(date, time);
ZonedDateTime zdt = ldt.atZone(zoneId);
Instant instant = zdt.toInstant(); // Use Instant (moment on the timeline in UTC) for data storage, exchange, serialization, database, etc.
if (null == firstInstant) {
firstInstant = instant; // Capture the first instant.
}
Duration duration = Duration.between(firstInstant, instant);
Long deltaInSeconds = duration.getSeconds();
double doubleDeltaInSeconds = deltaInSeconds.doubleValue();
timeVals.add(doubleDeltaInSeconds);
priceVals.add(price);
//System.out.println("deltaInSeconds: " + deltaInSeconds + " | price: " + price + " | index: " + index);
}
Double [] timeValsArray = timeVals.toArray(new Double[timeVals.size()]);
Double [] priceValsArray = timeVals.toArray(new Double[priceVals.size()]);
Double[] timeFeed = new Double[timeVals.size()];
Double[] priceFeed = new Double[priceVals.size()];
for(int x = 0;x<timeVals.size(); x++) {
timeFeed[x] = new Double (timeValsArray[x].doubleValue());
priceFeed[x] = new Double (priceValsArray[x]);
}
PolynomialFunctionLagrangeForm pflf = new PolynomialFunctionLagrangeForm(timeFeed,priceFeed);
}
According to the documentation, the PolynomialFunctionLagrangeForm constructor takes two double[] arrays, not Double[].
Hence you need to create a raw array and pass that:
...
double[] timeFeed = new double[timeVals.size()];
double[] priceFeed = new double[priceVals.size()];
for(int x = 0; x < timeVals.size(); x++) {
timeFeed[x] = timeValsArray[x].doubleValue();
priceFeed[x] = priceValsArray[x].doubleValue();
}
...
See also How to convert an ArrayList containing Integers to primitive int array? for some alternative ways to convert an ArrayList<T> (where T is a wrapper for a primitive type) to the corresponding raw array T[].
Note that there is also obviously a typo in your code:
Double [] priceValsArray = timeVals.toArray(new Double[priceVals.size()]);
needs to be
Double [] priceValsArray = priceVals.toArray(new Double[priceVals.size()]);

Find element in ArrayList Java

I have trouble finding elements, here is my code:
public static void main(String[] args) {
BufferedReader br = getFileReader("reader.csv");
ArrayList<Monitoring> col = getCollection(br);
//sort the collection on 'beginTime'
for (Monitoring x : col)
System.out.println(x.toString());
BeginTimeComparator beginTime = new BeginTimeComparator();
Collections.sort(col,beginTime);
System.out.println("Begin time:");
for (Monitoring x : col)
System.out.println(x.toString());
This is the part I have trouble with, I don't know how to search en get back the object with endTime 2015-03-10.
BTW this is one line of cvs data:
UnitId;BeginTime;EndTime;Type;Min;Max;Sum
14100072;2015-03-10 07:12:20;2015-03-10 7:13:20;Gps/GpsAccuracyGyroBias;0;0;0
//find the amount of elements that were sent on 'endTime' = 2015-03-10 (just the date)
EndTimeComparator endTime = new EndTimeComparator();
String findThis = "2015-03-10";
Collections.sort(col, endTime);
for(Monitoring x : col){
if(x.getEndTime().equals(findThis)){
System.out.println("Here is 'endTime= 2015-03-10' :");
System.out.println(x.toString());
}
}
I have tried this but both didn't work:
int index = Collections.binarySearch(col, findThis.toString(), null);
System.out.println("Here is 'endTime= 2015-03-10' :");
System.out.println(index);
Guessing that getEndTime() returns a LocalDateTime you can't compare a string with a type of LocalDateTime. You could try to parse the LocalDateTime to LocalDate and fill the 'findThis' variabel with a type of LocalDate.
Because code says more than a 1000 words:
EndTimeComparator endTime = new EndTimeComparator();
Collections.sort(col, endTime);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate findThis = LocalDate.parse("2015-03-10", dtf);
System.out.println("Here is 'endTime= 2015-03-10' :");
for (Monitoring x : col) {
if (x.getEndTime().toLocalDate().equals(findThis)) {
System.out.println(x.toString());
}
}
You need to provide Comparator for that null or Monitoring should implement comparable (both of them should compare items by time field that you need).
Collections.binarySearch(col, findThis.toString(), null);
According to the example data you provided
UnitId;BeginTime;EndTime;Type;Min;Max;Sum
14100072;2015-03-10 07:12:20;2015-03-10 7:13:20;Gps/GpsAccuracyGyroBias;0;0;0
endTime is "2015-03-10 7:13:20", not "2015-03-10", so using equals will not work. Instead, you could try using startsWith:
String findThis = "2015-03-10";
for (Monitoring x : col) {
if (x.getEndTime().startsWith(findThis)) {
System.out.println("Here is 'endTime= 2015-03-10': ");
System.out.println(x.toString());
}
}
Or even better: Instead of storing the begin and end times as strings, convert them to Date objects or similar when you read the objects from CSV.

Array and date format issue

I am a beginer in jquery and java.I have two string variables and a string array.I passed these 3 to a java servlet using a post request from javascript.Below is the code:
var stDate= $('#drpstart').jqxDateTimeInput('getText');
var edDate= $('#drpend').jqxDateTimeInput('getText');
var items = $("#target").jqxListBox('getItems');
var itemsid=[];
$("#jqxWidget").html('');
for (var i = 0; i < items.length; i++) {
itemsid[i]=items[i].value;
}
$.post('ActionItem',
{startdt:stDate,enddt:edDate,item:itemsid},function(responseJson) {
});
Then I access these variables and array at servlet side:
String starts=request.getParameter("startdt");
String ends=request.getParameter("enddt");
String[] myArray =request.getParameterValues("item");
if (myArray != null ) {
for (int i = 0; i < myArray.length; i++){
System.out.println(myArray[i]);
}
}
else {
System.out.println("null value");
}
but the myarray is geting a null value.How to get the values correctly to myarray?
Also my database table StockRegisterHeader contain field 'Date' with Date as datatype,so i converted the string variables starts and ends to Date format as below
SimpleDateFormat from = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat to = new SimpleDateFormat("yyyy-MM-dd");
Date startg = from.parse(starts); // 01/02/2014
Date endg = from.parse(ends);
Now I need to select data from 4 tables within this date range. I wrote the query as below:
String ss="SELECT Items.ParentID,Items.Name ,StockRegisterHeader.MovementType,
StockRegisterHeader.Date, UOM.Name,StockRegisterDetails.Quantity,
StockRegisterDetails.Rate from Items,StockRegisterHeader,UOM,StockRegisterDetails
where Items.ID = StockRegisterDetails.ItemID and
StockRegisterDetails.StockRegisterHeaderID = StockRegisterHeader.Id and
StockRegisterDetails.UOMID = UOM.ID and StockRegisterHeader.Date between '"+startg+"'
and '"+endg+"'";
rs=stmt.executeQuery(ss);
But the resultset object rs is showing null even if the database contain the requested data.I think this may be due to the date format. How to solve these two issues? I am using mysql database. Please help me.
try changing
String[] myArray =request.getParameterValues("item");
to
String[] myArray =request.getParameterValues("item[]"); //brackets must be specified to retrive array value

Categories

Resources