Date date1= new java.util.Date();
java.sql.Date Sqldob = new java.sql.Date(date1.getTime());
System.out.println("date" +Sqldob);
Time Sqldob1 = new Time(date1.getTime());
System.out.println("User Time: " +Sqldob1);
String yourTime="09:30:00";
SimpleDateFormat ra = new SimpleDateFormat("HH:mm:ss");
Date yourDate = ra.parse(yourTime);
Time sqlTime3 = new Time(yourDate.getTime());
System.out.println("your time"+sqlTime3);
if(Sqldob1.before(sqlTime3)){
Sqldob1 = sqlTime3;
System.out.println("inside loop");
}
In the code above I am comparing two time variables for equality, but it is giving me the same value -1 for all the types of input
You need to use the Date#before(Date),Date#after(Date) and Date#equals(Date) methods for basic date comparisons.
E.g:
Date d1 = new Date();
Date d2 = new Date();
if(d1.after(d2)){
// Do something
}
if(d1.before(d2)){
// Do something
}
if(d1.equals(d2)){
// Do something
}
You can use the Date#compareTo(Date) method also, but then, you need to interpret the output of the compareTo method accordingly.
As the docs say:
The value 0 if the argument Date is equal to this Date; a value less
than 0 if this Date is before the Date argument; and a value greater
than 0 if this Date is after the Date argument.
In your case, you are getting -1 because
new SimpleDateFormat("HHH:mm:ss"); is wrong. Should be new SimpleDateFormat("HH:mm:ss");
int compare= sqlTime3.compareTo(Sqldob1); This sqlTime3 has only time in it. The date is the epoch date as you've not mentioned that, and hence, its always going to be before new Date() which is today.
Your solution:- (Hope this addresses your problem)
java.util.Date date1= new java.util.Date();
Time Sqldob1 = new Time(date1.getTime());
System.out.println("User Time: " +Sqldob1);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 19); // Your hour
cal.set(Calendar.MINUTE, 30); // Your Mintue
cal.set(Calendar.SECOND, 00); // Your second
Time sqlTime3 = new Time(cal.getTime().getTime());
System.out.println("your time: "+sqlTime3);
if(Sqldob1.before(sqlTime3)){
Sqldob1 = sqlTime3;
System.out.println("inside loop");
}
You need to parse the date and call methods like before(), after() and equals() like this,
if(date.before(date1)){
System.out.println(" date is before date1 ");
}
if(date.after(date1)){
System.out.println(" date is after date1 ");
}
If both date and date1 are equal you can use equals method,
if(date.equals(date1)){
System.out.println(" date and date1 are equal");
}
Modern version:
LocalDateTime dateTime1 = LocalDateTime.now(ZoneId.systemDefault());
LocalDate dob = dateTime1.toLocalDate();
System.out.println("date " + dob);
LocalTime dob1 = dateTime1.toLocalTime();
System.out.println("User Time: " + dob1);
String yourTime = "09:30:00";
LocalTime time3 = LocalTime.parse(yourTime);
System.out.println("your time " + time3);
if (dob1.isBefore(time3)) {
dob1 = time3;
System.out.println("inside if statement");
}
When I ran this code this morning, it printed:
date 2017-07-07
User Time: 05:32:01.881
your time 09:30
inside if statement
The point is: With the old and now long outdated classes Date and Time it is easy not to get things right. With the modern classes I use here, it’s much easier to get them right.
Are you using java.sql types because you really need to get your date and time from a database and/or store them into one? This was what these were for, you shouldn’t really have used them for other purposes. I use “was” and “were” intentionally because you don’t need them for this purpose either anymore. With a new JDBC driver, you can get a LocalDateTime from the database and store one back, or depending on your column datatype get an Instant and convert it to LocalDateTime:
LocalDateTime dateTime2 = instantFromDb.atZone(ZoneId.systemDefault())
.toLocalDateTime();
PS Item 2. in SoduRahul’s answer gives the real and correct explanation of what went wrong in your program: though Time was meant for time-of-day only, your Sqldob1 ends up holding today’s date and sqlTime3 the date of the epoch (January 1, 1970), so the former will always be after the latter by their before method.
compareTo() method always return zero for equal and non-zero for unequal dates.
Related
I have this problem with calculating time difference in minutes.
Its working fine with exampples like calculating the difference between
2045 and 2300.
But when I want to calculate the difference between for example
2330 (today) and 0245 (tomorrow) I get a incorrect answer.
Code below:
// This example works
String dateStart = "2045";
String dateStop = "2300";
// This example doesnt work
//String dateStart = "2330";
//String dateStop = "0245";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HHmm");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (Exception e) {
e.printStackTrace();
}
long diff = d2.getTime() - d1.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println("Time in minutes: " + minutes + " minutes.");
Thanks in advance
Consider using LocalDate, LocalDateTime, LocalTime ZonedDateTime classes from java.time.* package introduced in Java 8. They are very handy in use as they can address various corner cases (e.g. measuring minutes across different time zones, or during autumn and spring time change).
The thing to you need to know when you calculate time difference is that:
LocalTime contains time only
LocalDate contains date only (no time)
LocalDateTime contains both (date + time.)
ZonedDateTime contains date + time + timezone
This implies that difference between times will be different when you compare with:
LocalTime you can diff only time so 20:45 and 23:30 gives 2:45 of difference
LocalDate you cannot calculate any time diffs (contains no time)
LocalDateTime you can specify date and time, e.g.: 20:45 on 1Jan and 23:30 on 3Jan . Time difference will be 2:45 and 2 days of difference, or 50:45.
ZonedDateTime - same as LocalDateTime plus you takes into account DayLightSavings, so if the clock is changed overnight - it will get reflected.
Here is a snippet for a LocalDateTime:
LocalDateTime today2045 = LocalDateTime.of(
LocalDate.now(),
LocalTime.parse("20:45"));
LocalDateTime tomorrow0230 = LocalDateTime.of(
LocalDate.now().plusDays(1),
LocalTime.parse("02:30"));
System.out.println("Difference [minutes]: " +
Duration.between(today2045, tomorrow0230).toMinutes());
For ZonedDateTime taking into account spring/autumn clock changes:
ZonedDateTime today2045 = ZonedDateTime.of(
LocalDate.now(),
LocalTime.parse("20:45"),
ZoneId.systemDefault());
ZonedDateTime tomorrow0230 = ZonedDateTime.of(
LocalDate.now().plusDays(1),
LocalTime.parse("02:30"),
ZoneId.systemDefault());
System.out.println("Difference [minutes]: " +
Duration.between(today2045, tomorrow0230).toMinutes());
Some info on constructors can be found in Oracle's tutorial here.
This is not working because when you create a new date with just a time in it, it's assuming the day is "today".
What you could do is:
// This example works
String dateStart = "2045";
String dateStop = "2300";
// This example doesnt work
//String dateStart = "2330";
//String dateStop = "0245";
// Custom date format
SimpleDateFormat format = new SimpleDateFormat("HHmm");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
} catch (Exception e) {
e.printStackTrace();
}
// MY ADDITION TO YOUR CODE STARTS HERE
if(d2.before(d1)){
Calendar c = Calendar.getInstance();
c.setTime(d2);
c.add(Calendar.DATE, 1);
d2 = c.getTime();
}
// ENDS HERE
long diff = d2.getTime() - d1.getTime();
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println("Time in minutes: " + minutes + " minutes.");
But you should consider using Java 8 new Date/Time features, or Joda Time.
You can add if statement to check if this is today, and if no you can add one day to this, since you are comparing time it wont be problem if you add full day
if(d2.before(d1)){
d2.setTime(d2.getTime()+86400000);
}
Try it out
This is a solved problem. If you look at the Joda Time library you'll find all the time and date manipulation functions you could possibly want:
In your case something along the lines of:
DateTime first = new DateTime(larger-time);
DateTime second = new DateTime(smaller-time);
DateTime difference = first.minusMillis(second.getMillis())
Joda will cope with all the odd edge conditions like rolling over between days/months/years, lengths of months, leap years, daylight savings, timezones...
I am calling a stored procedure in a database.
Two of its parameters requires date and time in sql date format.
String x = new SimpleDateFormat("MM-dd-yyyy").format(new Date()) + " 00:00:00 AM";
String y = new SimpleDateFormat("MM-dd-yyyy").format(new Date()) + " 11:59:00 PM";
Date fromDate = null;
Date toDate = null;
try {
fromDate = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss a").parse(x);
toDate = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss a").parse(y);
} catch (ParseException ex) {
}
CallableStatement proc_stmt = con.prepareCall("{ call someproc(?,?) }");
proc_stmt.setDate(1, (java.sql.Date) fromDate);
proc_stmt.setDate(2, (java.sql.Date) toDate);
I believe if i send just the date(excluding time), the code works, but its of no use to me as the database does not generate correct results.
When i run the above code I get
ClassCastException:java.util.Date cannot be cast to java.sql.Date
Any solution?
Use java.sql.Timestamp class which holds date and time for sql fields, and CallableStatement#setTimestamp:
proc_stmt.setTimestamp(1, new java.sql.Timestamp(fromDate.getTime());
create new object of java.sql date and then pass the java.util date in it.
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
I usually go for along the lines of
proc_stmt.setDate(1, new java.sql.Date(fromDate.getTime()));
Why are you formatting a Date to a String and then parsing it again? You shouldn't need a string representation at all. Avoid string conversions as far as you can - you're not really interested in the text representation of the date; you're just trying to specify a value.
You should be able to use:
// TODO: Consider time zones
Calendar calendar = Calendar.getInstance();
// Clear the time part of the calendar (leaving you with "start of day")
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
Timestamp start = new Timestamp(calendar.getTimeInMillis());
// Adjust to "end of day"
calendar.add(Calendar.DATE, 1);
calendar.add(Calendar.MILLISECOND, -1);
Timestamp end = new Timestamp(calendar.getTimeInMillis());
CallableStatement statement = con.prepareCall("{ call someproc(?,?) }");
statement.setTimestamp(1, start);
statement.setTimestamp(2, end);
Note that I've switched to using java.sql.Timestamp instead of java.sql.Date as it looks like you really do want a date and time whereas java.sql.Date only represents a date.
A couple of other points:
If you could use Joda Time, it would make the first part of the code simpler. Joda Time is a much better date/time API in general.
I would suggest you change your stored procedure to use an exclusive end time if possible. That way you can just specify the start of today and the start of tomorrow. You don't need to worry about the granularity of the value, because you can always create abutting but non-overlapping intervals. In particular, I've currently only set end to the end of the day down to the last millisecond - but java.sql.Timestamp
Probably there will be simply and fast answer but I still cant find out why is the result of
Date date = new Date(60000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
dateStr - 01:01:00
Still one hour more. Time zone? How can I set it without it? Thanks.
Date represents a specific moment in time, not a duration. new Date(60000) does not create "one minute". See the docs for that constructor:
Initializes this Date instance using the specified millisecond value. The value is the number of milliseconds since Jan. 1, 1970 GMT.
If you want "one minute from now" you'll probably want to use the Calendar class instead, specifically the add method.
Update:
DateUtils has some useful methods that you might find useful. If you want the elapsed time in HH:mm:ss format, you might try DateUtils.formatElapsedTime. Something like:
String dateStr = DateUtils.formatElapsedTime(60);
Note that the 60 is in seconds.
Three ways to use java.util.Date to specify one minute:
1. Using SimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")) as shahtapa said:
Date date = new Date(60*1000); //one min.
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
2. Using java.util.Calendar as kabuko said:
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Other calendar.set() statements can also be used:
calendar.set(Calendar.MILLISECOND,60*1000); //one min.
calendar.set(1970,0,1,0,1,0); //one min.
3. Using these setTimeZone and Calendar ideas and forcing Calendar to
UTC Time-Zone
as Simon Nickerson said:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.clear();
calendar.set(Calendar.MINUTE,1); //one min.
Date date = calendar.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
String dateStr = dateFormat.format(date);
System.out.println("Result = " + dateStr); //Result should be 00:01:00
Note: I had a similar issue: Date 1970-01-01 was in my case -3 600 000 milliseconds (1 hour late) java.util.Date(70,0,1).getTime() -> -3600000
I recommend to use TimeUnit
"A TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units. A TimeUnit does not maintain time information, but only helps organize and use time representations that may be maintained separately across various contexts. A nanosecond is defined as one thousandth of a microsecond, a microsecond as one thousandth of a millisecond, a millisecond as one thousandth of a second, a minute as sixty seconds, an hour as sixty minutes, and a day as twenty four hours."
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html
Date date = new Date(); // getting actual date
date = new Date (d.getTime() + TimeUnit.MINUTES.toMillis(1)); // adding one minute to the date
I have a Timestamp and Date variables and i want to compare it for equality (only date part of course). It was surprise for me that contructor Date(long) saves time part, so this code does not work correct:
date = resultSet.getDate(1);
timestamp = resultSet.getTimestamp(2);
//...
if (date.equals(new Date (timestamp.getTime())) ...
I solve this with code like:
DateFormat dateFormat = new SimpleDateFormat ("yyyyMMdd");
if (date.equals(dateFormat.parse(dateFormat.format(timestamp)))) ...
Or i can convert timestamp to date in sql query, but i need a timestamp representation too. Is there a better way to cut a time part from Timestamp.
Java 8 approach of conversion:
Date date = Date.valueOf(timestamp.toLocalDateTime().toLocalDate());
And vice versa:
Timestamp timestamp = Timestamp.valueOf(date.toLocalDate().atStartOfDay());
Using the method from this answer we get:
date = resultSet.getDate(1);
timestamp = resultSet.getTimestamp(2);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date);
cal2.setTimeInMillis(timestamp.getTime());
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
It's worth reading the linked answer as it talks about the shortcomings of this method with respects to timezones and so on (and some of the other answers to that question give alternate approaches which you may prefer).
You have three options with this one.
First is to use Yoda time and class DateTimeComparator.getDateOnlyInstance()
Second is to use commons from apache and DateUtils.isSameDay()
Third use the [Calendar] and set the time and compare the year, month and day of year only. As Dave Webb proposed.
Another approach is to use the "day" part of the epoch value:
Date d = new Date();
Timestamp t = new Timestamp(d.getTime());
long dateEpochDays = d.getTime() % (1000*60*60*24);
long timeStampEpochDays = t.getTime() %(1000*60*60*24);
System.out.println("date: " + dateEpochDays + " timestamp: " + timeStampEpochDays);
I need a Java program to get the current date without a timestamp:
Date d = new Date();
gives me date and timestamp.
But I need only the date, without a timestamp. I use this date to compare with another date object that does not have a timestamp.
On printing
System.out.println("Current Date : " + d)
of d it should print May 11 2010 - 00:00:00.
A java.util.Date object is a kind of timestamp - it contains a number of milliseconds since January 1, 1970, 00:00:00 UTC. So you can't use a standard Date object to contain just a day / month / year, without a time.
As far as I know, there's no really easy way to compare dates by only taking the date (and not the time) into account in the standard Java API. You can use class Calendar and clear the hour, minutes, seconds and milliseconds:
Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.AM_PM);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
Do the same with another Calendar object that contains the date that you want to compare it to, and use the after() or before() methods to do the comparison.
As explained into the Javadoc of java.util.Calendar.clear(int field):
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
edit - The answer above is from 2010; in Java 8, there is a new date and time API in the package java.time which is much more powerful and useful than the old java.util.Date and java.util.Calendar classes. Use the new date and time classes instead of the old ones.
You could always use apache commons' DateUtils class. It has the static method isSameDay() which "Checks if two date objects are on the same day ignoring time."
static boolean isSameDay(Date date1, Date date2)
Use DateFormat to solve this problem:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateFormat2 = new SimpleDateFormat("MM-dd-yyyy");
print(dateFormat.format(new Date()); // will print like 2014-02-20
print(dateFormat2.format(new Date()); // will print like 02-20-2014
I did as follows and it worked: (Current date without timestamp)
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date today = dateFormat.parse(dateFormat.format(new Date()));
DateFormat dateFormat = new SimpleDateFormat("MMMM dd yyyy");
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
You can get by this date:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
print(dateFormat.format(new Date());
You could use
// Format a string containing a date.
import java.util.Calendar;
import java.util.GregorianCalendar;
import static java.util.Calendar.*;
Calendar c = GregorianCalendar.getInstance();
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c);
// -> s == "Duke's Birthday: May 23, 1995"
Have a look at the Formatter API documentation.
The accepted answer by Jesper is correct but now outdated. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.
java.time
Instead use the java.time framework, built into Java 8 and later, back-ported to Java 6 & 7 and further adapted to Android.
If you truly do not care about time-of-day and time zones, use LocalDate in the java.time framework ().
LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );
Today
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). If critical, confirm the zone with your user.
Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;
Moment
If you care about specific moments, specific points on the timeline, do not use LocalDate. If you care about the date as seen through the wall-clock time used by the people of a certain region, do not use LocalDate.
Be aware that if you have any chance of needing to deal with other time zones or UTC, this is the wrong way to go. Naïve programmers tend to think they do not need time zones when in fact they do.
Strings
Call toString to generate a string in standard ISO 8601 format.
String output = localDate.toString();
2014-05-06
For other formats, search Stack Overflow for DateTimeFormatter class.
Joda-Time
Though now supplanted by java.time, you can use the similar LocalDate class in the Joda-Time library (the inspiration for java.time).
LocalDate localDate = new LocalDate( 2014, 5, 6 );
Also you can use apache commons lib DateUtils.truncate():
Date now = new Date();
Date truncated = DateUtils.truncate(now, Calendar.DAY_OF_MONTH);
Time will be set to 00:00:00 so you can work with this date or print it formatted:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(dateFormat.format(now); // 2010-05-11 11:32:47
System.out.println(dateFormat.format(truncated); // 2010-05-11 00:00:00
private static final DateFormat df1 = new SimpleDateFormat("yyyyMMdd");
private static Date NOW = new Date();
static {
try {
NOW = df1.parse(df1.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
}
I think this will work. Use Calendar to manipulate time fields (reset them to zero), then get the Date from the Calendar.
Calendar c = GregorianCalendar.getInstance();
c.clear( Calendar.HOUR_OF_DAY );
c.clear( Calendar.MINUTE );
c.clear( Calendar.SECOND );
c.clear( Calendar.MILLISECOND );
Date today = c.getTime();
Or do the opposite. Put the date you want to compare to in a calendar and compare calendar dates
Date compareToDate; // assume this is set before going in.
Calendar today = GregorianCalendar.getInstance();
Calendar compareTo = GregorianCalendar.getInstance();
compareTo.setTime( compareToDate );
if( today.get( Calendar.YEAR ) == compareTo.get( Calendar.YEAR ) &&
today.get( Calendar.DAY_OF_YEAR ) == compareTo.get( Calendar.DAY_OF_YEAR ) ) {
// They are the same day!
}
Here's an inelegant way of doing it quick without additional dependencies.
You could just use java.sql.Date, which extends java.util.Date although for comparisons you will have to compare the Strings.
java.sql.Date dt1 = new java.sql.Date(System.currentTimeMillis());
String dt1Text = dt1.toString();
System.out.println("Current Date1 : " + dt1Text);
Thread.sleep(2000);
java.sql.Date dt2 = new java.sql.Date(System.currentTimeMillis());
String dt2Text = dt2.toString();
System.out.println("Current Date2 : " + dt2Text);
boolean dateResult = dt1.equals(dt2);
System.out.println("Date comparison is " + dateResult);
boolean stringResult = dt1Text.equals(dt2Text);
System.out.println("String comparison is " + stringResult);
Output:
Current Date1 : 2010-05-10
Current Date2 : 2010-05-10
Date comparison is false
String comparison is true
If you really want to use a Date instead for a Calendar for comparison, this is the shortest piece of code you could use:
Calendar c = Calendar.getInstance();
Date d = new GregorianCalendar(c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).getTime();
This way you make sure the hours/minute/second/millisecond values are blank.
I did as follows and it worked:
calendar1.set(Calendar.HOUR_OF_DAY, 0);
calendar1.set(Calendar.AM_PM, 0);
calendar1.set(Calendar.HOUR, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);
Date date1 = calendar1.getTime(); // Convert it to date
Do this for other instances to which you want to compare. This logic worked for me; I had to compare the dates whether they are equal or not, but you can do different comparisons (before, after, equals, etc.)
I was looking for the same solution and the following worked for me.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.clear(Calendar.HOUR);
calendar.clear(Calendar.MINUTE);
calendar.clear(Calendar.SECOND);
calendar.clear(Calendar.MILLISECOND);
Date today = calendar.getTime();
Please note that I am using calendar.set(Calendar.HOUR_OF_DAY, 0) for HOUR_OF_DAY instead of using the clear method, because it is suggested in Calendar.clear method's javadocs as the following
The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and
the the resolution rule for the time of day is applied. Clearing one
of the fields doesn't reset the hour of day value of this Calendar.
Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.
With the above posted solution I get output as
Wed Sep 11 00:00:00 EDT 2013
Using clear method for HOUR_OF_DAY resets hour at 12 when executing after 12PM or 00 when executing before 12PM.
Here is my code for get only date:
Calendar c=Calendar.getInstance();
DateFormat dm = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date date = new java.util.Date();
System.out.println("current date is : " + dm.format(date));
Here is full Example of it.But you have to cast Sting back to Date.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format MM dd yyyy HH:mm:ss.SSSSSS
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("MM dd yyyy HH:mm:ss.SSSSSS");
Date thisDate = new Date();//changeFormat.parse("10 07 2012");
System.out.println("Current Date : " + thisDate);
changeFormat.format(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(thisDate);
System.out.println(strDateOutput);
}
}