Apache POI Excel Date - java

I'm trying to do automations in Java with Apache POI and I need to convert a date dd-MM-yyyy into the format that Excel saves dates. like 31.12.2022 equals to 44926 in Excel. so I searched a bit and discovered that the number equals the days that have passed between 1.1.1900 and in this example 31.12.2022 so i searched for a function that calculates this but only got some that have irregular differences than from excel. I also tried with ChatGPT but no luck.
Date date1 = new Date(year, month, day);// some date
Date date2 = new Date(1900,1,1); // some other date
long difference = date1.getTime() - date2.getTime();
int differenceDays = (int) (difference / (1000 * 60 * 60 * 24));
return differenceDays;
I used this code and as I said earlier it'ss not the same result I get in Excel at first I thought it was just a difference of 4 that is always the same so I just added +4 but then I realized that this doesnt work because sometimes its 3 or smth else.

Related

Why are the get methods crossed out in this code? [duplicate]

This question already has answers here:
Code fragments are being struck out in Eclipse, why?
(3 answers)
Closed 7 years ago.
I have a piece of code here to calculate someone's age with the SQL date type in java.
The code works fine, but however you can't see it in the code pasted here, but in my netbeans environment the get methods are crossed out, but only in this line:
LocalDate datumDB = LocalDate.of(gbdat.getYear() + 1900, gbdat.getMonth() + 1,
gbdat.getDate());
someone any idea why?
this line isn't crossed out:
int leeftijd = datumVanVandaag.getYear() - datumDB.getYear();
this is my code:
private void checkSpelerGeschiktVoorPloeg(Persoon p) {
Date gbdat = p.getGbDatum();
LocalDate datumVanVandaag = LocalDate.now();
LocalDate datumDB = LocalDate.of(gbdat.getYear() + 1900, gbdat.getMonth() + 1, gbdat.getDate());
int leeftijd = datumVanVandaag.getYear() - datumDB.getYear();
}
The strikeout indicates that those methods are deprecated. You should use either java.util.Calendar or the new Java 8 Datetime API (which is the new-and-improved API that the LocalDate you're using is part of) to calculate these values for a date.
For instance the API document says:
#Deprecated
public int getYear()
Deprecated. As of JDK version 1.1, replaced by Calendar.get(Calendar.YEAR) - 1900.
Returns a value that is the result of subtracting 1900 from the year that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

Comparing to get seconds difference between java and mysql datetime

I read a mysql date time field into one string e.g.
String arriveTime = rs1.getString("arriveTime");
Next step I try to get the current date and time using java to be similar format like the one I got from mysql.
DateFormat outDf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateTimer=null;
Date date = Calendar.getInstance().getTime();
currentDateTimer=outDf.format(date);
How can I minus the currentDateTime and arriveTime to get the net results in seconds. I would prefer to do it purely via java
First, I would not read a MySQL date-time into a String. I would change this,
String arriveTime = rs1.getString("arriveTime");
to
java.sql.Date arriveTime = rs1.getDate("arriveTime");
Then you can use basic subtraction to get the result in milliseconds, then divide by a thousand to get that in seconds - so
long diff = new java.util.Date().getTime() - arriveTime.getTime();
System.out.println(diff / 1000);
I read a mysql date time field into one string
If the column is varchar type it is ok you can read it using resultsetObject.getString()
But if your column type is Date then is it always recommended to get the value using resultset.getDate()
Mysql stores date in the format yyyy-MM-dd
I try to get the current date and time using java to be similar format
like the one I got from mysql.
When you do resultset.getDate() it will give you the java.sql.Date in format yyyy-MM-dd

Android unix timestamp - Converter [duplicate]

This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 8 years ago.
In my android app I'm creating a timestamp this way:
final BackupInfo backupInfo = new BackupInfo(description, System.currentTimeMillis(), backupContacts.size());
eg, using System.currentTimeMillis()
Now I convert it back to date format using:
public static String getDate(long time)
{
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(time);
String date = DateFormat.format("dd-MM-yyyy HH:mm:ss", cal).toString();
return date;
}
And it works fine.
But now I'm receiving a timestamp from a server and the date String I receive from getDate is not the correct date.
Practical case:
My app generates this timestamp: 1403022230766
getDate returns this date: 17-06-2014 05:23:50 which is correct to my eyes.
Now the problem comes in, I get this timestamp from the server: 1403022360
getdate returns this date: 16-01-1970 18:43:42 which is totally wrong, it should be close to the timestamp generated by my app.
The timestamp returned by the server is 3 digits less in size. But if I go to an online converter, like this one and I put 1403022360 (the TS generated by the server) I get a correct date.
Can anyone explain me why this difference and what am I doing wrong in my getDate method that I can't decode the timestamp received from the server?
Your server is returning your timestamp in seconds, so multiply by 1000 to get milliseconds.
The online converters work properly because they assume that the that if the number is large enough, then it is in milliseconds and if it's short then it is in seconds.
Java/Android dates are all long types so they can hold milliseconds for additional precision.

Modify date without modifying time

With JodaTime, without using the 'plus' or 'minus' functions and using the least lines of code, how can I set a new date without modifying the time?
My first attempt was to store the 'time' parts of the DateTime in separate ints using getHoursOfDay() and getMinutesOfHour() etc - then create a new DateTime with the required date and set the hours, minutes, and seconds back again. But this method is pretty clunky, and I was wondering if there was a less verbose method for doing this - ideally with just one line of code.
For example:
22/05/2013 13:40:02 >>>> 30/08/2014 13:40:02
Is JodaTime a must? Basic way to do this is
1. extract just time from timestamp.
2. add this to just date
long timestamp = System.currentTimeMillis(); //OK we have some timestamp
long justTime = timestamp % 1000 * 60 * 60 * 24;// just tiem contains just time part
long newTimestamp = getDateFromSomeSource();//now we have date from some source
justNewDate = newTimestamp - (newTimestamp % 1000 * 60 * 60 * 24);//extract just date
result = justNewDate + justTime;
Something like this.
Previously accepted answer were removed by moderator, as it contains only link to javadoc.
Here is edited version.
You could do it like this
DateTime myDate = ...
myDate.withDate(desiredYear, desiredMonth, desiredDayOfMonth);
JavaDoc is here: DateTime.withDate(int year, int month, int dayOfMonth)
use withFields like this:
new DateTime().withFields(new LocalDate(2000,1,1))
This will set all date time fields of the DateTime to those that are contained in the LocalDate - year, month and day in this case. This will work with any ReadablePartial implementation like YearMonth for example.

java.sql.timestamp versus date

I am using Derby database with Java and Eclipse. I have a table which has a TIMESTAMP field and I use a model to populate a JTable from it. I am finding timestamp and data and java.sql and java.utils very confusing. The following line of code errors with cannot cast date to timestamp. mod is the model interfacing Derby table and JTable.
int rowcount = mod.getRowCount();
java.sql.Timestamp ts = (java.sql.Timestamp) mod.getValueAt(rowcount-1,1);
My objective is to get the date of the most recent record and subtract 30 days then run an sql query on the same database to find all the records more recent than that date. How do I recover the first timestamp, subtract the 30 days, then construct a query with the result of the subtraction as the condition in a WHERE clause. Sounds simple but I am having such difficulty that I feel I must be missing some fundamental principal. I thought conversion to long and back again might be the route but came up against the same cast problem.
Timestamp is declared as
public class Timestamp extends java.util.Date { ... }
Therefore you can't cast date to timstamp, you could create a timestamp from a date.
Timstamp ts = new Timestamp( date.getTime() );
To subtract 30 days this sequence might be helpful:
Calendar cal = new GregorianCalendar();
cal.setTime( date.getTime() );
cal.add( Calendar.DAY_OF_MONTH, -30 );
Date d30 = cal.getTime();
Anyway I would try to perform this using only SQL.

Categories