I have a table in SQLite having date column defined as Numeric type
KEY_DRIVER_STAT_DAT + " NUBMERIC"
Now I'mm inserting data in KEY_DRIVER_STAT_DAT columns as
values.put(KEY_DRIVER_STAT_DAT, DateTime.now().getMillis());
How can I get the records from this table where KEY_DRIVER_STAT_DAT is between
Current date ?
Dealing with dates by their milliseconds values is tricky. When you insert record with millisecond value as date you insert it with the value of current moment. You need to search all records which are in time period from start of date (time of 00:00) and to the end of date (time of 23:59). Take a look at this example:
/*Suppose your DateTime is Joda's DateTime class*/
import java.util.*;
import org.joda.time.*;
// Two functions to help retrive start and end of date
public static DateTime getStart(DateTime date) {
return new DateTime(date.year().get(), date.monthOfYear().get(), date.dayOfMonth().get(), 0, 0);
}
public static DateTime getEnd(DateTime date) {
return new DateTime(date.year().get(), date.monthOfYear().get(), date.dayOfMonth().get(), 23, 59);
}
// Code to make clause and parameters for select-statement
DateTime now = DateTime.now();
DateTime start = getStart(now);
DateTime end = getEnd(now);
String yourClause = "KEY_DRIVER_STAT_DAT >= ? AND KEY_DRIVER_STAT_DAT <= ?";
String[] params = new String[] {String.valueOf(start.getMillis()), String.valueOf(end.getMillis())};
System.out.println("clause: " + yourClause);
System.out.println("parameters: " + Arrays.toString(params));
Related
I have 2 database columns in MySQL database showing start and end times of the appointments.
it is stored as '2019-01-01 00:00:00'. How to I take that time (assuming it is in UTC) and convert it to local system time (for example PC set to EST) and then display it inside start and end columns of the TableView?
I setup tableview columns like this:
appTableViewStartColumn.setCellValueFactory(new PropertyValueFactory<Appointment, Calendar>("start"));
appTableViewEndColumn.setCellValueFactory(new PropertyValueFactory<Appointment, Calendar>("end"));
And this is my code for method called getAllAppointments:
public static ObservableList<Appointment> getAllAppointments() throws SQLException, Exception {
DatabaseConnection.makeConnection();
String sqlStatement = "SELECT appointmentId, customerId, type, start, end, customerName FROM appointment LEFT JOIN customer " +
"USING (customerId)";
Query.makeQuery(sqlStatement);
ResultSet result = Query.getResult();
while (result.next()) {
int appointmentId = result.getInt("appointmentId");
int customerIdIn = result.getInt("customerId");
String type = result.getString("type");
String customerName = result.getString("customerName");
// Following gets date as string, then converts it to Calendar
String startString = result.getString("start");
String endString = result.getString("end");
Calendar start = stringToCalendar(startString);
Calendar end = stringToCalendar(endString);
Appointment appointmentResult = new Appointment (appointmentId, customerIdIn, type, start, end, customerName);
allAppointments.add(appointmentResult);
}
This is the method that I used to convert string to Calendar object:
public static Calendar stringToCalendar (String stringDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(stringDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar;
}
I assume you use the DATETIME column type in the db.
I recommend doing yourself a favor and going with the java.time API instead of using Calendar.
You can retrieve the time directly via ResultSet and apply the appropriate conversions to either LocalDateTime or ZonedDateTime. The former has the benefit of having a StringConverter implementation in the JavaFX API, but for configuring the display, both work.
Data Retrieval
final ZoneId est = ZoneId.of("America/New_York"); // ZoneId.systemDefault();
while (result.next()){
...
Timestamp time = result.getTimestamp("start"); // utc is offset 0; no offset required
ZonedDateTime zTime = time.toInstant().atZone(est);
LocalDateTime start = zTime.toLocalDateTime();
...
}
Column Setup
TableColumn<Appointment, LocalDateTime> appTableViewStartColumn = ...
...
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
appTableViewStartColumn.setCellFactory(col -> new TableCell<Appointment, LocalDateTime>() {
#Override
protected void updateItem(LocalDateTime item, boolean empty) {
super.updateItem(item, empty);
setText(item == null ? "" : formatter.format(item));
}
});
First of all part of your code is missing from the question (stringToCalendar())
But assuming that you are attempting to parse a string date in UTC/GMT format and then exploit the Calendar functionality in another timezone, the following should work:
// Parse date - use your format
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(strDate);
//instantiates a calendar using the current time in the specified timezone
Calendar cal= Calendar.getInstance(TimeZone.getTimeZone("GMT"));
cal.setTime(date);
//change the timezone
cal.setTimeZone(TimeZone.getDefault());
// or cal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cal.get(Calendar.HOUR_OF_DAY);
//...
Part of the code comes from: How to change TIMEZONE for a java.util.Calendar/Date
I want to iterate the one month in each row.
This my code, and when run this it doesn't iterate the months.
/** function receive date and integer then add the integer to the date then return the result date.
(e.g. if you send 2013/07/13 and 5 to this function the function will return 2013/07/18 */
public static Date addDayToOracleDate(oracle.jbo.domain.Date date, int days)
{
if (date != null)
{
Calendar c1 = Calendar.getInstance();
c1.setTime(date.getValue());
c1.add(Calendar.DATE, days);
java.util.Date javaUtilDate = c1.getTime();
long javaMilliseconds = javaUtilDate.getTime();
java.sql.Date javaSqlDate = new java.sql.Date(javaMilliseconds);
return new oracle.jbo.domain.Date(javaSqlDate);
}
return null;
}
public void genrateActionLSNR(ActionEvent actionEvent) {
BindingContainer bc = BindingContext.getCurrent().getCurrentBindingsEntry();
DCIteratorBinding CEmpLoans1Iterator = (DCIteratorBinding)bc.get("CEmpLoans1Iterator");
DCIteratorBinding CEmpLoans1DIterator = (DCIteratorBinding)bc.get("CEmpLoansD2Iterator");
Number loanValue = (Number)CEmpLoans1Iterator.getCurrentRow().getAttribute("LoanValue");
Number noOfMonths = (Number)CEmpLoans1Iterator.getCurrentRow().getAttribute("NoOfMonths");
Date firstInstallmentDate = (Date)CEmpLoans1Iterator.getCurrentRow().getAttribute("FirstInstallmentDate");
Number result = (Number)loanValue.div(noOfMonths);
Date hh = firstInstallmentDate;
for(int i=0; i<noOfMonths.getValue();i++){
addDayToOracleDate(hh, 30);
bc.getOperationBinding("CreateInsert1").execute();
CEmpLoans1DIterator.getCurrentRow().setAttribute("InstallmentVal", result);
CEmpLoans1DIterator.getCurrentRow().setAttribute("LoansMonths", hh);
System.out.println(hh);
//bc.getOperationBinding("Commit").execute();
}
You're assuming that each month is 30 days long, which is obviously wrong. If you want to add one month to the date, try c1.add(Calendar.MONTH, 1);
What about creating new method at Application Module
and execute something like the following SQL statement using PreparedStatement
SELECT SYSDATE +:NO_OF_DAYS FROM DUAL;
replace sysdate and dual with your column and table
My program reading data from a database and I want to convert some fields to date format (date and time separately). I can do this from sql query but is it possible to do from java code.
date format in table = MMDDHHMISS (month day hour minute sec)
and these are sql queries now I'm using-
TO_CHAR(TO_DATE(DATETIMECOLUMN, 'MMDDHH24MISS'),'DD/MM/YYYY') AS MY_DATE
TO_CHAR(TO_DATE(DATETIMECOLUMN, 'MMDDHH24MISS'),'HH24:MI:SS') AS MY_TIME
Thanks in advance!
Here’s a suggestion:
DateTimeFormatter databaseStringFormatter = DateTimeFormatter.ofPattern("MMddHHmmss");
String sampleDatabaseString = "1129225145";
MonthDay myDate = MonthDay.parse(sampleDatabaseString, databaseStringFormatter);
LocalTime myTime = LocalTime.parse(sampleDatabaseString, databaseStringFormatter);
System.out.println("Date: " + myDate + ". Time: " + myTime + '.');
The above prints
Date: --11-29. Time: 22:51:45.
MonthDay is a date without a year, useful for birthdays and other anniversary dates.
Unless there are specific reasons to avoid it, I think you should rather change the datatype of your database column to datetime or similar and then retrieve LocalDateTime objects from your result set as shown in this answer. This would free you from any conversion from string to date and time in either the database query or in Java.
I have an Oracle database which contains a field W_PLANNED_DATE: 19/03/2013 10:55:00 (Date)
In Java I put this value into a variable:
Date dteBeginOrWaitingItem = orWaitinglist.getWPlannedDate();
value: 2013-03-19
Now, what happend to my time? I need this to fill the schedulecomponent of primefaces.
How can i get a full date and time value
eventResourceAvailPerDay.addEvent(new DefaultScheduleEvent(reason, dteBeginOrWaitingItem, dteEndOrWaitingItem, "waitingitem"));
This method puts the event at 12:00 PM as there is no other time or the time is just 00:00:00
I know how to use the Calendar class but it just lets me set the date, the time seems to be empty but in database view I have a date time value.
Mybean
import java.util.Date;
#ManagedBean(name="scheduleController")
#SessionScoped
public class ScheduleController implements Serializable {
private Date dteBeginOrWaitingItem, dteEndOrWaitingItem;
//methods
try
{
//eventWaitinglist.clear();
OrWaitinglistDao orWaitinglistDao = new OrWaitinglistDaoImpl();
waitingEvents = orWaitinglistDao.getOrWaitinglistKeysByResource(rKey);
int i = 0;
Iterator<OrWaitinglist> it2 = waitingEvents.iterator();
while (it2.hasNext())
{
orWaitinglist = it2.next();
dteBeginOrWaitingItem = (Date) orWaitinglist.getWPlannedDate();
dteEndOrWaitingItem = orWaitinglist.getWPlannedDate();
//dteEndOrWaitingItem = orWaitinglist.getWPlannedDate();
reason = orWaitinglist.getWDescription();
eventResourceAvailPerDay.addEvent(new DefaultScheduleEvent(reason, dteBeginOrWaitingItem, dteEndOrWaitingItem, "waitingitem"));
i += 1;
System.out.println("EventWaiting: " + i + " " + dteBeginOrWaitingItem + " " + dteEndOrWaitingItem + " " + reason);
}
}
catch(java.util.EmptyStackException Ex)
{
System.out.println(Ex.getMessage());
}
WORKING UPDATE:
Bean:
try
{
//eventWaitinglist.clear();
OrWaitinglistDao orWaitinglistDao = new OrWaitinglistDaoImpl();
waitingEvents = orWaitinglistDao.getOrWaitinglistKeysByResource(rKey);
int i = 0;
Iterator<OrWaitinglist> it2 = waitingEvents.iterator();
while (it2.hasNext())
{
orWaitinglist = it2.next();
Long wPlannedDate = orWaitinglist.getWPlannedDate().getTime();
if (wPlannedDate != 0) {
Date wPlannedDateConverted = new Date(wPlannedDate);
dteBeginOrWaitingItem = convertDate(0, 0, wPlannedDateConverted);
dteEndOrWaitingItem = convertDate(orWaitinglist.getWDuration().intValue(), orWaitinglist.getWAdditionalTime().intValue(), wPlannedDateConverted);
}
reason = orWaitinglist.getWDescription();
DefaultScheduleEvent newResourceEvent = new DefaultScheduleEvent(reason, dteBeginOrWaitingItem, dteEndOrWaitingItem, orWaitinglist);
newResourceEvent.setStyleClass("waitingitem");
eventResourceAvailPerDay.addEvent(newResourceEvent);
}
}
catch(java.util.EmptyStackException Ex)
{
System.out.println(Ex.getMessage());
}
public static Date convertDate(Integer wDuration, Integer wAdditionalTime, Date availDate)
{
Calendar cal = Calendar.getInstance();
Integer wAdditionalTimeHours, wAdditionalTimeMinutes;
Integer wDurationHours, wDurationMinutes;
if(wAdditionalTime != 0 || wDuration != 0) {
if (wAdditionalTime !=0) {
wAdditionalTimeHours = (int) Math.floor (wAdditionalTime / 60);
wAdditionalTimeMinutes = wAdditionalTime - (wAdditionalTimeHours * 60);
cal.setTime(availDate);
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
cal.add(Calendar.MINUTE, wAdditionalTimeMinutes);
cal.add(Calendar.HOUR_OF_DAY, wAdditionalTimeHours);
}
if (wDuration != 0) {
wDurationHours = (int) Math.floor (wAdditionalTime / 60);
wDurationMinutes = wAdditionalTime - (wDurationHours * 60);
cal.setTime(availDate);
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
cal.add(Calendar.MINUTE, wDurationMinutes);
cal.add(Calendar.HOUR_OF_DAY, wDurationHours);
}
} else {
cal.setTime(availDate);
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND));
}
return cal.getTime();
}
Model update:
<property name="WPlannedDate" type="timestamp">
<column length="7" name="W_PLANNED_DATE">
<comment>Planned date</comment>
</column>
</property>
java.sql.Date will not return time component, you should use java.util.Date while creating your preparedstatement or any other way your are querying the db.
EDIT:
Using java.util.Date with sql query can be tricky as query will expect java.sql.Date. It works for me in Spring. If you dont want to use this then you can use java.sql.Timestamp also.
See below documentation:
8.3.12 DATE, TIME, and TIMESTAMP
There are three JDBC types relating to time:
The JDBC DATE type represents a date consisting of day, month, and
year. The corresponding SQL DATE type is defined in SQL-92, but it is
implemented by only a subset of the major databases. Some databases
offer alternative SQL types that support similar semantics. The JDBC
TIME type represents a time consisting of hours, minutes, and seconds.
The corresponding SQL TIME type is defined in SQL-92, but it is
implemented by only a subset of the major databases. As with DATE,
some databases offer alternative SQL types that support similar
semantics. The JDBC TIMESTAMP type represents DATE plus TIME plus a
nanosecond field. The corresponding SQL TIMESTAMP type is defined in
SQL-92, but it is implemented by only a very small number of
databases. Because the standard Java class java.util.Date does not
match any of these three JDBC date/time types exactly (it includes
both DATE and TIME information but has no nanoseconds), JDBC defines
three subclasses of java.util.Date to correspond to the SQL types.
They are:
java.sql.Date for SQL DATE information. The hour, minute, second, and
millisecond fields of the java.util.Date base class should be set to
zero. If the number of milliseconds supplied to the java.sql.Date
constructor is negative, the driver will compute the date as the
number of milliseconds before January 1, 1970. Otherwise, the date is
computed as the specified number of milliseconds after January 1,
1970.
java.sql.Time for SQL TIME information. The year, month, and day
fields of the java.util.Date base class are set to 1970, January, and
1. This is the "zero" date in the Java epoch. java.sql.Timestamp for SQL TIMESTAMP information. This class extends java.util.Date by adding
a nanoseconds field.
EDIT: if you are using .xml for hibernate change type to timestamp instead of date.
<property name="yourdate" column="YOUR_DATE" type="timestamp" />
therefore you have time on your database and can use simpledateformat
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy-HH:mm");
dateFormat.format(orWaitinglist.getWPlannedDate());
Instead of java.sql.Date, java.sql.Timestamp and the matching methods should be used. The oracle type DATE is equivalent to the JDBC and SQL-standard type TIMESTAMP.
A driver is required by the JDBC spec to exclude the time part when one of the get/setDate methods are used.
I have an activity where i save some info to my database.
I have two textviews one for date (yyyy-MM-dd) and one for time (HH:mm).
if i save datetime as a TEXT, i can sort then desc properly,but CAN i find with sqlite query last/7/30 days records?An example of this query when are the datetime TEXT?
First you should calculate the date range you want to analize, then convert its boundaries into the text format (you can use some date formatting ustilities). Then you should query the Db with converted dates as parameters.
Suppose you want last 30 days list:
Calendar theEnd = Calendar.getInstance();
Calendar theStart = (Calendar) theEnd.clone();
theStart.add(Calendar.DAY_OF_MONTH, -30);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String start = dateFormat.format(theStart.getTime());
String end = dateFormat.format(theEnd.getTime());
// Now you have date boundaries in TEXT format
Cursor cursor = db.rawQuery("SELECT * FROM table WHERE timestamp BETWEEN "+start+" AND "+end);