Compare java getTime time with strings representing a date - java

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

Related

Convert String to java.sql.Date object in "YYYY" format

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.

gregorian calendar java error

I can't print GregorianCalendar
package Tests;
import java.util.Date;
import java.util.GregorianCalendar;
public class Data
{
public static void main(String[] args)
{
GregorianCalendar time = new GregorianCalendar(1999, 2, 2);
System.out.println(time);
}
}
I receive this
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Belgrade",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=119,lastRule=java.util.SimpleTimeZone[id=Europe/Belgrade,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=?,YEAR=1999,MONTH=2,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=2,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]
How I can print it?
you can use this like :-
GregorianCalendar calendar = new GregorianCalendar();
Date now = calendar.getTime();
System.out.println(now);
or
Calendar cal2 = new GregorianCalendar(2010, 9, 26); // allocate with the specified date
cal2.get(Calendar.DAY_OF_WEEK); // 1 (Sunday) to 7 (Saturday)
when you call
System.out.println(time)
you've actually calling the toString() method of the Calendar instance (in this case, a GregorianCalendar one)
In order to have a properly formatted date, use SimpleDateFormat as stated in the Javadoc
https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
java.time
The modern solution uses the LocalDate class instead. Avoid GregorianCalendar as it is now obsolete.
LocalDate ld = LocalDate.of( 1999 , Month.FEBRUARY , 2 ) ;
ld.toString(): 1999-02-02
The toString method uses the standard ISO 8601 formats. For other formats, use the DateTimeFormatter class. Search Stack Overflow for more examples and discussion, as that has beeen covered many many times.
Generally best to let DateTimeFormatter automatically localize for you.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( locale ) ;
String output = ld.format( f ) ;
mardi 2 février 1999
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.

java date of today [duplicate]

This question already has answers here:
How to convert java.util.Date to java.sql.Date?
(17 answers)
Closed 7 years ago.
I am trying to generate the date of today. But I always get: "1969-12-31" as the output.
here my code:
java.util.Date d1 = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(d1.getDate());
I want to add it in a sql table, what am I doing wrong?
Any suggestions?
d1.getDate() will give an int representing the current date. Eg: 23.
What you need is d1.getTime().
java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTime().getTime());
java.time
In Java 8 and later you should make use of the new java.time framework. These new classes supplant the old classes which have proven so troublesome.
Time Zone
Note that time zone is crucial in determining a date.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate localDate = LocalDate.now( ZoneId );
java.sql.Date d = java.sql.Date.valueOf( localDate );
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.
The getDate() function is deprecated.
Try use this:
java.util.Date d1 = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(d1.getTime());
java.util.date.getDate documentation says that method is deprecated and time that it is returning is actually a base epoch time which begins from 1970-01-01.Learn more about it on https://en.wikipedia.org/wiki/Unix_time
In order to get the actual date you need to do the following:
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());

How do I print a millisecond count from epoch as a date-time in UTC using Java?

I am trying to use Java to format a time in milliseconds into a date in UTC. I have the following code:
long ms = 1427590800000;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT);
cal.setTimeInMillis(ms);
Date date = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(date)); // 2015-03-29 02:00:00
This is printing a time in BST (i.e. using the default time-zone) rather than UTC. It seems like the time-zone being set on the calendar has no bearing on the date being printed.
The actual time in UTC is shown by the following python snippet:
import datetime
ms = 1427590800000
print datetime.datetime.utcfromtimestamp(ms/1000.0) # 2015-03-29 01:00:00
Setting the default JVM time-zone to "UTC" results in the correct date being printed, but this doesn't seem like a safe solution.
java.time
The modern approach uses the industry-leading java.time classes.
Parse as an Instant, a moment in UTC with a resolution of nanoseconds.
long input = 1_427_590_800_000L ;
Instant instant = Instant.ofEpochMilli( input ) ;
ISO 8601
Generate a string in standard ISO 8601 format.
String output = instant.toString() ;
2015-03-29T01:00:00Z
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.
You need to set the timezone to the formatter before formatting if you want a desired timezone.
Use dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); and then call dateFormat.format(date)

Dates in Java, how to manipulate the year?

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.

Categories

Resources