I have a date and duration. I need to add the duration to date. Date's format is timestamp, duration's - Long (milliseconds). How can I wright criteria to deal this issue?
Practically i have something like this:
03-17-2014 21:24:57 + 2523566;
If you want to do it in Java and have a java.sql.Date and a long:
public java.sql.Date dateAdd(java.sql.Date inputDate, long duration)
{
return new java.sql.Date(inputDate.getTime() + duration);
}
A java.sql.Timestamp can be used in place of a java.sql.Date in either the argument or the return value, if required.
Related
I've set column in mysql db with type String, int, double, float, date, time, datetime
If String, int, double, float data type can be declare as "sidf" in mysqli_stmt_bind_param , what about date, time, datetime?
And also in java , let say i create constructor name Req
Public class Req{
Public Req(String name, int qty, double price, float pay, date? , time?, datetime?){}
}
What data type for those three (dare, time and datetime)?
You insert it like any other string.
Although it's saved in the database as Time, Date or DateTime, it is still a string.
So you'd use s.
Example:
$stmt = $mysqli->prepare('insert into my_database (my_date) values (?)');
$my_date = '2016-10-06 12:00:00';
$stmt->bind_param('s', $my_date);
$stmt->execute();
you can use java.util.Date, java.sql.Time and java.sql.Timestamp
Public class Req{
Public Req(String name, int qty, double price, float pay, Date date,Time time,Timestamp datetime){
}
}
You can declare date in mysql using the DATE keyword which has a format of 'yyyy-mm-dd'
About the time you can use the TIME keyword in mysql which has the format of 'HHH:MM:SS'
About the Datetime you can simply use the DATETIME keyword that has this format 'YYYY-MM-DD HH:MM:SS'
So you could follow this syntax
CREATE TABLE table_name (
col1 DATE,
col2 TIME,
col3 DATETIME);
and when dealing with it in java you can use
java.sql.Date for the DATE type
java.sql.Time for the TIME type
java.sql.Timestamp for the DATETIME
We have a case, where we require only the day and the month and thus would use the java.time.MonthDay (Javadocs) to represent that information.
We are aware that we could create our own JPA object for persistence or just use the java.sql.Date object, but that generally requires an unrequired year information.
Another way is to call the method .atYear(int) (Javadoc) (with a fictitious year) on it and receive a java.time.LocalDate (Javadoc), which can be easily converted to java.sql.Date. But this is prone to missunderstandings in the future (and also persist the year information).
Is there some "elegant"/supposed solution for this case? Or is there a replacement for SQL that supports the whole new date and time API for Persistence.
Another case would be java.time.YearMonth (Javadoc).
Thanks for reading!
Since SQL databases don't have a type compatible with MonthDay, use a VARCHAR columns, and simply use toString() and MonthDay.parse().
Or use a custom DateTimeFormatter, if you don't like the --12-03 format.
The default format will correctly sort, as a string.
here are the code snippets:
// column define:
#Column(name = "date", columnDefinition = "mediumint", nullable = false)
#Convert(converter = MonthDayIntegerAttributeConverter.class)
protected MonthDay date;
// converter define:
public class MonthDayIntegerAttributeConverter implements AttributeConverter<MonthDay, Integer> {
#Override
public Integer convertToDatabaseColumn(MonthDay attribute) {
return (attribute.getMonthValue() * 100) + attribute.getDayOfMonth();
}
#Override
public MonthDay convertToEntityAttribute(Integer dbData) {
int month = dbData / 100;
int day = dbData % 100;
return MonthDay.of(month, day);
}
}
I wonder why the setTime method behaves exactly like setDate, date without time, or instead to set the time on 2014-07-01 13:21:01 it is set on 2014-07-01 00:00:00 ?!?!
Is setTime deprecated?
Should I use setTimestamp???
Databases other than Oracle actually do distinguish between three different datatypes:
DATE only date, no time
TIME only time of the day, no date
TIMESTAMP both, date & time.
JDBC tries to abstract standard SQL concepts and the above three datatypes are defined by ANSI SQL and thus JDBC needs to support them.
As Oracle's date always includes the time, you have to use setTimestamp() otherwise the time is lost when you store it in the database.
setTime() Method :
The java.util.Calendar.setTime(Date) method sets Calendar's time with the given Date.
Following is the declaration for java.util.Calendar.setTime() method
public final void setTime(Date date)
This method does not return a value.
Example :
The following example shows the usage of java.util.calendar.setTime() method.
package com.tutorialspoint;
import java.util.*;
public class CalendarDemo {
public static void main(String[] args) {
// create a calendar
Calendar cal = Calendar.getInstance();
// get the current time
System.out.println("Current time is :" + cal.getTime());
// create new date and set it
Date date = new Date(95, 10, 10);
cal.setTime(date);
// print the new time
System.out.println("After setting Time: " + cal.getTime());
}
}
SetTimestamp Method :
Sets the designated parameter to the given timestamp and calendar values.
Syntax
public void setTimestamp(java.lang.String sCol,
java.sql.Timestamp x,
java.util.Calendar c)
I'm generating one date and saving in a database through hibernate, and when I get the value and I compare with the value before it was inserted. The result is not equal!
I created the date as following
Date rightnow = Calendar.getInstance().getTime();
Task t1 = new Task("My task", rightnow);
taskDao.saveOrUpdate(t1);
Task taskR1 = taskDao.get(t1.getIdTask());
assertEquals("They should have to be equal dates",taskR1.getDate(),t1.getDate());
I'm getting this error
<2014-04-11 23:13:13.0> is different to <Fri Apr 11 23:13:13 CEST 2014>
java.lang.AssertionError:
They should have to be equal dates
expected:<2014-04-11 23:13:13.0>
but was:<Fri Apr 11 23:13:13 CEST 2014>
Extra info related with the problem
Class Task
#Entity
#Table(name = "t_task")
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idTask")
private long idTask;
...
#Column(name = "date")
private Date date;
...
Mysql table t_task
CREATE TABLE IF NOT EXISTS `mytask`.`t_task` (
`idTask` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`date` DATETIME NOT NULL
...
I created a new hashCode() and equals() functions in Task, with only date field and even so it is different.
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Task))
return false;
Task other = (Task) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
return true;
}
Any idea?
This is a complete mess caused by the java.sql.Timestamp messed up design, and by Hibernate returning instances of this class. Indeed, you're storing a java.util.Date instance into your entity. Hibernate transforms that to a java.sql.Timestamp to insert it in the database. But when it reads the data from the database, it doesn't trasform back the Timestamp into a java.util.Date. That works fine, because Timestamp extends Date.
But Timestamp should never have extended Date. Indeed, Date is precise up to the millisecond, whereas Timestamp is precise up to the nanosecond. To be able to compare the nanoseconds parts of two Timestamp, Timestamp overrides the equals() method, but breaks its general contract by doing so. The end result is that you can have date.equals(timestamp) being true, but timestamp.equals(date) being false.
My advice: never compare Date instances with equals(). Use compareTo() instead.
Sun's explanation, working with java client level (not with Hibernate), in the javadoc for java.sql.Timestamp, it states:
Quote:
public class Timestamp extends Date
A thin wrapper around java.util.Date that allows the JDBC API to
identify this as an SQL TIMESTAMP value. It adds the ability to hold
the SQL TIMESTAMP nanos value and provides formatting and parsing
operations to support the JDBC escape syntax for timestamp values.
Note: This type is a composite of a java.util.Date and a separate
nanoseconds value. Only integral seconds are stored in the
java.util.Date component. The fractional seconds - the nanos - are
separate. The Timestamp.equals(Object) method never returns true when
passed a value of type java.util.Date because the nanos component of a
date is unknown. As a result, the Timestamp.equals(Object) method is
not symmetric with respect to the java.util.Date.equals(Object)
method. Also, the hashcode method uses the underlying java.util.Date
implementation and therefore does not include nanos in its
computation.
Due to the differences between the Timestamp class and the
java.util.Date class mentioned above, it is recommended that code not
view Timestamp values generically as an instance of java.util.Date.
The inheritance relationship between Timestamp and java.util.Date
really denotes implementation inheritance, and not type inheritance.
#Test
public void testTimestampVsDate() {
java.util.Date date = new java.util.Date();
java.util.Date stamp = new java.sql.Timestamp(date.getTime());
assertTrue("date.equals(stamp)", date.equals(stamp)); //TRUE
assertTrue("stamp.compareTo(date)", stamp.compareTo(date) == 0); //TRUE
assertTrue("date.compareTo(stamp)", date.compareTo(stamp) == 0); //FALSE
assertTrue("stamp.equals(date)", stamp.equals(date)); //FALSE
}
From javadoc we can figure out that:
Timestamp = java.util.Date + nanoseconds
and
The Timestamp.equals(Object) method never returns true when passed a
value of type java.util.Date because the nanos component of a date is
unknown.
Timestamp compareTo() function
public int compareTo(java.util.Date o) {
if(o instanceof Timestamp) {
// When Timestamp instance compare it with a Timestamp
// Hence it is basically calling this.compareTo((Timestamp))o);
// Note typecasting is safe because o is instance of Timestamp
return compareTo((Timestamp)o);
} else {
// When Date doing a o.compareTo(this)
// will give wrong results.
Timestamp ts = new Timestamp(o.getTime());
return this.compareTo(ts);
}
}
I would suggest you look at what type you are using to store the date in the database. For instance, an Oracle DATE only has precision down to the second level while TIMESTAMP can have down to millisecond like you would with Java date.
http://docs.oracle.com/cd/B19306_01/server.102/b14220/datatype.htm#CNCPT413
For those who are looking for an easy unit testing answer to comparing dates, I have used a SimpleDateFormatter to compare dates as Strings. This allows you to specify the precision you are seeking in the comparison without a bunch of math.
SimpleDateFormatter formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
assertEquals(formatter.format(someExpectedDate), formatter.format(someActualDate));
You can modify the format to fit your needs.
The two dates are of different classes (one is a java.util.Date, the other is java.sql.Timestamp), so they are not the same.
Try this to check the date values:
assertEquals(new Date(taskR1.getDate().getTime()), t1.getDate());
Why does this code return 0001-02-05?
public static String getNowDate() throws ParseException
{
return Myformat(toFormattedDateString(Calendar.getInstance()));
}
I changed the code to:
public static String getNowDate() throws ParseException
{
Calendar temp=Calendar.getInstance();
return temp.YEAR+"-"+temp.MONTH+"-"+temp.DAY_OF_MONTH;
}
And now it returns 1-2-5.
Please, help me get the actual date. all i need is the Sdk date.
Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH are int constants (just look up in the API doc)...
So, as #Alex posted, to create a formatted String out of a Calendar instance, you should use SimpleDateFormat.
If however you need the numeric representations of specific fields, use the get(int) function:
int year = temp.get(Calendar.YEAR);
int month = temp.get(Calendar.MONTH);
int dayOfMonth = temp.get(Calendar.DAY_OF_MONTH);
WARNING! Month starts from 0!!! I've made some mistakes because of this!
Use SimpleDateFormat
new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());
You are using constants to be used with the Calendar.get() method.
Why not use SimpleDateFormat?
public static String getNowDate() {
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
}
You are doing it wrong. Change to:
return temp.get(Calendar.YEAR)+"-"+ (temp.get(Calendar.MONTH)+1) +"-"+temp.get(Calendar.DAY_OF_MONTH);
Also, you may want to look into Date:
Date dt = new Date();
//this will get current date and time, guaranteed to nearest millisecond
System.out.println(dt.toString());
//you can format it as follows in your required format
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(dt));