I want to create a java.sql.Date object of the format "YYYY". It should have only the year. I researched a lot but couldn't find a way to do it.
tl;dr
Never use terrible java.sql.Date class, badly designed with multiple flaws.
Use either java.time.Year object, or an integer.
myPreparedStatement.setObject( … , Year.of( 2018 ) ) ;
…or, while using Year in other parts of your code:
myPreparedStatement.setInt( … , Year.of( 2018 ).getValue() ) ;
java.time
The modern solution uses the java.time classes that years ago supplanted the terrible old date-time classes of SimpleDateFormat, java.util.Date, java.sql.Date, and so on.
The Year class neatly represents a year value. Using this class in your code gives you type-safety and makes your code more self-documenting.
Parsing a string input.
Year y = Year.parse( "2018" ) ;
Parsing an integer input.
Year y = Year.of( 2018 ) ; // Integer literal.
JDBC
As of JDBC 4.2 we can directly exchange java.time types.
Exchange Year object
I do not know if this includes the Year class and YEAR data type in MySQL. But give it a shot. If not, make a feature request to your JDBC driver vendor to extend support. Seems like a justifiable expectation given the fact that MySQL has an explicit YEAR type.
myPreparedStatement.setObject( … , y ) ;
Retrieval.
Year y = myResultSet.getObject( … , Year.class ) ;
Exchange integer
If your JDBC driver cannot use java.time.Year directly, use integer.
myPreparedStatement.setInt( … , y.getValue() ) ; // Pass year as an integer number.
Retrieval.
Year y = Year.of( myResultSet.getInt( … ) ) ; // Retrieve integer, convert to `Year` object.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You need to create a java.util.Date and then convert this to a java.sql.Date using the constructor that takes in a long.
Example:
String year = "2018";
DateFormat format = new SimpleDateFormat("yyyy");
java.util.Date utilDate = format.parse(year);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
However, it's not "only a year". Dates in Java always have a time component, so this isn't possible - it will be "1 Jan 2018 00:00:00 GMT" in my example. Is this close enough to what you want, or could you refine your question?
In addition, a java.sql.Date extends java.util.Date, so ideally you'd use the former wherever possible to satisfy the Liskov substitution principle.
Related
Is there any method in MySql which can return the name of days between two dates. For example 06/11/207 is start date and 12/11/2017 is end date then I need to get the output as:
monday,tuesday,wednesday,thursday,friday,saturday,sunday
you can try this :
you can take F_TABLE_NUMBER_RANGE function from this link:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=47685
declare #start_date datetime
declare #end_date datetime
declare #days int
select #start_date = '06/11/2017'
select #end_date = '12/11/2017'
select #days = datediff(dd,#start_date,#end_date) +1
select
[Date] = dateadd(dd,number-1,#start_date),
[Day of Week] = datename(weekday,dateadd(dd,number-1,#start_date))
from
dbo.F_TABLE_NUMBER_RANGE( 1, #days )
order by
number
This I have tried and working for me cheers !
tl;dr
Use Java. Auto-localize.
myResultSet.getObject( … , LocalDate.class ) // Retrieve a `LocalDate` object from your database.
.getDayOfWeek() // Fetch the `DayOfWeek` object appropriate for this date. Ex: DayOfWeek.MONDAY
.getDisplayName( // Generate a String of the name of day-of-week.
TextStyle.FULL , // How long or abbreviated?
Locale.US // Or Locale.CANADA_FRENCH, etc.
)
Monday
Details
Generally best to do such transformations within your app rather than SQL, IMHO.
Java has an industry-leading date-time framework now in Java 8 and later, the java.time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
With JDBC 4.2 and later, you can directly exchange java.time objects with your database.
LocalDate localDate = myResultSet.getObject( … , LocalDate.class ) ; // Retrieval.
myPreparedStatement.setObject( … , localDate ) ; // Insert/Update.
The DayOfWeek enum offers seven existing objects, one for each day of the week. Use the getDisplayName method to generate an automatically localized name for the day-of-week.
DayOfWeek dow = localDate.getDayOfWeek() ;
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
lundi
Or, US English:
DayOfWeek dow = localDate.getDayOfWeek() ;
String output = dow.getDisplayName( TextStyle.FULL , Locale.US ) ;
Monday
Compare LocalDate objects with isBefore and isAfter and other methods. Loop each date incrementally by calling LocalDate::plusDays.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I have stored the date of a specific method each time it gets executed in ab sqlite database in 3 columns (one for the day, the month and the year).
Now I want to compare it to the date of the actutal day the user uses the app. With
Date currentTime = Calendar.getInstance().getTime()
I get this date, but how am I able to compare it to the strings I get from my database? Thank you!
Using java.time
Your Question is a duplicate of many others. So briefly…
Use java.time classes rather than the troublesome old legacy date-time classes. For Android, use libraries from the ThreeTen-Backport and ThreeTenABP projects.
Get today’s date.
ZoneId z = ZoneId.of( "America/Montreal" ) )
LocalDate today = LocalDate.now( z );
Get to parts of the date.
int y = today.getYear() ;
int m = today.getMonthValue() ;
int d = today.getDayOfMonth() ;
Query the database.
myPreparedStatement.setInt( 1 , y ) ;
myPreparedStatement.setInt( 2 , m ) ;
myPreparedStatement.setInt( 3 , d ) ;
As others suggested, you should be using date-time types in your database to store date-time values rather than mere ints for the pieces.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Try this:
SimpleDateFormat formattedDate = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formattedDate.format(date);
It will give you your date as shown in the Template. Now simply build a String out of your SQLite data in the same way (dd/MM/yyyy) and you cam simply compare them like shown in this post: https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
I know how to retrieve timestamp with milliseconds:
to_char(systimestamp ,'YYYY-MM-DD HH24:MI:SS,FF9')
Can anyone please advise, is the timestamp data type sufficient to store the date with milliseconds or can I use varchar2? I am trying to insert this value from Java.
Yes, TIMESTAMP allows precision down to nanoseconds if you want it.
If you only need milliseconds, you just want a TIMESTAMP(3) column.
Use a java.sql.Timestamp (which again goes down to nanoseconds, if you need it to) on the Java side. Note that you should avoid doing your to_char conversion if possible - perform any string conversions you need client-side; fetch data as a timestamp, and send it as a timestamp.
tl;dr
Use smart objects, not dumb strings. Use java.time for nanosecond resolution.
myResultSet.getObject( … , LocalDateTime.class )
java.time
The Answer by Jon Skeet is correct, but now outdated. The java.sql.Timestamp class is supplanted by the java.time classes such as Instant and LocalDateTime.
The java.time classes have a resolution of nanoseconds, more than enough for your milliseconds.
Oracle database seems to have a TIMESTAMP type that is equivalent to the SQL-standard type TIMESTAMP WITHOUT TIME ZONE. That means it lacks any concept of time zone or offset-from-UTC. For such a column, use LocalDateTime in Java as it too lacks any concept of zone/offset.
LocalDateTime ldt = myResultSet.getObject( … , LocalDateTime.class ) ;
For storing into a field of type similar to SQL-standard TIMESTAMP WITH TIME ZONE where do have respect for zone/offset, use Instant:
Instant instant = Instant.now() ; // Capture current moment as fine as nanoseconds. In practice, we get microseconds in Java 9, but only milliseconds in Java 8.
As of JDBC 4.2 and later, we can directly exchange java.time objects with the database via PreparedStatement.setObject and ResultSet.getObject. So use these smart objects rather than mere strings to communicate date-time values.
The java.time classes generate strings in standard ISO 8601 formats. Just call toString.
String output = instant.toString() ;
String output = ldt.toString() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I'm trying to assign a XMLGregorianCalendar date to a java.sql.Timestamp var, like this...
var1.setTimeStamp(Timestamp.valueOf(var2.getXMLGregorianCalendar().toString()))
But apparently, this is not working, and throws an exception...
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
And I've tried this, as well:
var1.setTimeStamp((Timestamp) var2.getXMLGregorianCalendar().getTime())
but...
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Timestamp
Any ideas..? Thanks!
I've found the answer:
Timestamp timestamp = new Timestamp(var2.getXMLGregorianCalendar().toGregorianCalendar().getTimeInMillis());
var1.setTimeStamp(timestamp);
tl;dr
Try to avoid legacy date-time classes. But if handed a javax.xml.datatype.XMLGregorianCalendar, convert to modern java.time.Instant class. No need to ever use java.sql.Timestamp.
myPreparedStatement.setObject(
… ,
myXMLGregorianCalendar // If forced to work with a `javax.xml.datatype.XMLGregorianCalendar` object rather than a modern java.time class…
.toGregorianCalendar() // …convert to a `java.util.GregorianCalendar`, and then…
.toZonedDateTime() // …convert to modern `java.time.ZonedDateTime` class.
.toInstant() // Adjust to UTC by extracting an `Instant` object.
)
Retrieving from a database, as of JDBC 4.2 and later.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
java.time
FYI, the terribly troublesome old date-time classes have been supplanted by the java.time classes.
javax.xml.datatype.XMLGregorianCalendar is replaced by java.time.ZonedDateTime.
java.util.GregorianCalendar is replaced by java.time.ZonedDateTime. Note new conversions methods added to the old class.
java.sql.Timestamp is replaced by java.time.Instant, both representing a moment in UTC with a resolution of nanoseconds.
Avoid using XMLGregorianCalendar. But if you must interface with old code not yet updated for java.time types, convert. As an intermediate step, convert to GregorianCalendar as seen in the code of your Question.
java.util.GregorianCalendar gc = myXMLGregorianCalendar.toGregorianCalendar() ;
Now use the new convenient conversion method added to the old GregorianCalendar class, to get a modern java.time.ZonedDateTime object.
ZonedDateTime zdt = gc.toZonedDateTime() ; // Convert from legacy class to modern class.
Adjust from that particular time zone to UTC. Extract an Instant object which is a moment always in UTC, by definition.
Instant instant = zdt.toInstant() ; // Adjust from some time zone to UTC.
As of JDBC 4.2, we can directly exchange java.time objects with the database. So no need to ever touch java.sql.Timestamp again.
myPreparedStatement.setObject( … , instant ) ;
Retrieval:
Instant instant = myResultSet.getObject( … , Instant.class ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I have a Date object in Java. Sometimes the date's year is set to 17. When I go to output it using a SimpleDateFormat, it gets printed out as 0017. All my years are going to be in the 2000's. Is there a way to check if the year is belowe a certain value and then add 2000 to it if it is? Then once you do that, how do you recreate the Date object to use the new year? Seems like everything in the Date object is deprecated.
I would use a Calendar:
Date myDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int year = cal.get(Calendar.YEAR);
if(year < 2000)
cal.add(Calendar.YEAR, 2000); // add two thousand years
If you use Calendar or Joda Time (a better choice) you can get and set the year (or other fields)
Your year shouldn't be 17 in the first place. I would try to correct the problem at source rather than patch it later.
First of all, Date.getYear returns CurrentYear - 1900, not 2000, and it looks like you'll want to do that increment every time.
But since it's deprecated, you shouldn't use it in the first place, if possible. The API recommends you use the calendar class instead: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html
java.time
If by Date you mean java.util.Date, that terribly designed class in now obsolete, years ago supplanted by the java.time classes defined in JSR 310.
Convert to its replacement, Instant, using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Both Instant and java.util.Date represent a moment in UTC. For any given moment, both time-of-day and date vary around the globe by zone. If you want to see the date through the wall-clock time of a particular time zone, apply ZoneId to get a ZonedDateTime.
ZoneID z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDatetTime zdt = instant.atZone( z ) ;
Now interrogate for the year.
int year = zdt.getYear() ;
Adjust. If that date in the different year is not valid (February 29 in non leap year), the ZonedDateTime class adjusts.
if( year < 1000 ) {
zdt = zdt.withYear( year + 2000 ) ; // You might also want to check for negative numbers. I'll omit that from this demo.
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.