Query data between two dates - java

I need to get data between two dates from the Mongodb data that hosted in online server. I tried this code and it's working good in my Localhost (local data & live data). But when I uploaded the app in online and it's not working properly in Live.
The results are not accurate in live site. It fetches some records before and after the specified dates. For example, I give the dates 01-02-2018 and 28-02-2018, and the results are coming with records of 31-01-2018 and 01-03-2018.
I think the problem is dates are stored in UTC timezone ( 2018-02-15T23:33:30.000Z ).
Code:
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date fromDate = format.parse(from + " 00:00:00");
Date toDate = format.parse(to + " 23:59:59");
Calendar cal = Calendar.getInstance();
cal.setTime(order.getOrderDate());
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
String strDate = sdf.format(cal.getTime());
Date orderDate = sdf.parse(strDate);
for(Order order : orders){
if(orderDate.after(fromDate) || orderDate.equals(fromDate) && orderDate.before(toDate) || orderDate.equals(toDate)){
//do something
}
}

java.util.Date doesn't have a timezone in it, so there's no point in parsing and formatting the order date. Formatting converts it to a String and parsing converts it back to a Date, which is pointless, because the order date is already a Date object.
You must set the timezone in the first formatter (the format variable), and then parse the from and to dates: they'll be set to the respective dates and times at Kolkata's timezone - in this case it's valid, because you have strings and want to convert them to dates.
Then you make your comparison using extra parenthesis to avoid any ambiguities (as pointed in the comments).
And there's no point in setting the Date to a Calendar, just to get it back later - the Calendar instance has no purpose in your code.
And the call to getOrderDate shouldn't be inside the for loop?
The full code will be like this:
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
// from and to dates are from Kolkata's timezone, so the formatter must know that
format.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
// dates will be equivalent to this date and time in Kolkata, although
// the date itself doesn't store the timezone in it
Date fromDate = format.parse(from + " 00:00:00");
Date toDate = format.parse(to + " 23:59:59");
for(Order order : orders){
Date orderDate = order.getOrderDate();
// note the extra parenthesis, they make all the difference
if( (orderDate.after(fromDate) || orderDate.equals(fromDate)) &&
(orderDate.before(toDate) || orderDate.equals(toDate)) ) {
....
}
}
If you have Java >= 8, it's better to use the java.time API:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
ZoneId zone = ZoneId.of("Asia/Kolkata");
ZonedDateTime fromDate = LocalDate
// parse "from" string
.parse(from, fmt)
// start of day at Kolkata timezone
.atStartOfDay(zone);
ZonedDateTime toDate = LocalDate
// parse "to" string
.parse(to, fmt)
// get start of next day
.plusDays(1).atStartOfDay(zone);
// convert the Date to ZonedDateTime
for (Order order : orders) {
ZonedDateTime orderDate = order.getOrderDate().toInstant().atZone(zone);
if ((orderDate.isAfter(fromDate) || orderDate.isEqual(fromDate)) && (orderDate.isBefore(toDate))) {
...
}
}
It's a different code because this API introduces new types and concepts, but it's quite a improvement from the previous API (Date and Calendar are messy, buggy and outdated).
Take some time to study this API, it's totally worth it: https://docs.oracle.com/javase/tutorial/datetime/

Related

Date selector based on months in Java

I have code in Java for Selenium Webdriver TestNG. Is for comparing if the date on the website is same as today date.
Problem is that date on webpage dateOnWebpage for 11th April 2018 is in format
Today 4/11/2018
So I made selecter to compare date formats if months < 10 if(javaDateSelector < 10) than date to compare is in format M/dd/yyyy else is in format MM/dd/yyyy.
Is there better way to code it than I made it? Because I needed to parse date to string and than to int to compare it and code is quite long.
#Test(priority=3)
public void test3DateCheck() throws Exception
{
String dateOnWebpage = driver.findElement(By.xpath("//div[#id='homeCalendarSection']/div/div[2]/table/tbody/tr/td/div/ul/li")).getText();
System.out.println("Today Date on webpage is : " + dateOnWebpage);
//DateFormat dateFormat1 = new SimpleDateFormat("M/dd/yyyy");
DateFormat dateFormat1 = new SimpleDateFormat("MM");
Date date = new Date();
String javaDate1 = dateFormat1.format(date);
int javaDateSelector = Integer.parseInt(javaDate1);
if(javaDateSelector < 10)
{
DateFormat dateFormat2 = new SimpleDateFormat("M/dd/yyyy");
String javaDate2 = dateFormat2.format(date);
System.out.println("Today Date from Java is : " + javaDate2);
Assert.assertEquals(dateOnWebpage, "Today " + javaDate2);
}
else
{
DateFormat dateFormat3 = new SimpleDateFormat("MM/dd/yyyy");
String javaDate3 = dateFormat3.format(date);
System.out.println("Today Date from Java is : " + javaDate3);
Assert.assertEquals(dateOnWebpage, "Today " + javaDate3);
}
}
If you don’t care whether the date on the web page is written with leading zero for month and day of month or not and just want to test whether the date is correct:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("'Today' M/d/uuuu");
LocalDate today = LocalDate.now(ZoneId.of("Pacific/Norfolk"));
System.out.println("Today is " + today);
LocalDate observedDate = LocalDate.parse(dateOnWebpage, dateFormatter);
Assert.assertEquals(today, observedDate);
Rather than testing the string I am parsing the date and testing it. Even though the pattern has one M and one d in it, parsing two-digit months and two-digits day of month poses no problem.
If on the other hand you also want to test that the date on the web page is written without any leading zeroes, it’s best to test the string, like you already did:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("M/d/uuuu");
LocalDate today = LocalDate.now(ZoneId.of("Pacific/Norfolk"));
String todayString = today.format(dateFormatter);
System.out.println("Today is " + todayString);
Assert.assertEquals("Today " + todayString, dateOnWebpage);
Again, even though the pattern has one M and one d in it, two digits will be printed if the month or the day of month is greater than 9. What else could the format method do? If you require two-digit day of month always, put dd in the format pattern string.
In both snippets please fill in your desired time zone where I put Pacific/Norfolk since it is never the same date everywhere on the globe.
I am using and recommending java.time, the modern Java date and time API. DateFormat and SimpleDateFormat are not only long outdated, they are also notoriously troublesome. Date is just as outdated. I would avoid those classes completely. The modern API is generally so much nicer to work with.
Link: Oracle tutorial: Date Time explaining how to use java.time.

Java Date generate in different timezone that tomcat is running [duplicate]

This question already has answers here:
How to set time zone of a java.util.Date?
(12 answers)
Closed 5 years ago.
I have a dates stored in mysql with no timezone, like 2001-01-10 00:00:00.
I have tomcat running in timezone +10:00 for example.
I need to generate a Date() that have no offset int the object.
If I do this:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTime( new Date(/*from 2001-01-10 00:00:00*/) );
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date newDate = cal.getTime();
The result Date object still having the zoneinfo and zoneoffset reporting to server timezone, not UTC.
I need to generate a Date() Object that have ZERO TIME, but mantain the date stored in mysql, independent of tomcat timezone.
In other words, I want to generate date with zero hour/min/sec independent of server timezone.
The date generated shows 2001-01-01T00:00:00.000+1400
the time is zero but offset is +14:00.
I want to generate 2001-01-01T00:00:00.000+0000
The mysql datatime is DATETIME
The Date object does not keep timezone information, imagine it as a class with only a long property which stores the number of milliseconds that passed from 1970.
The SimpleDateFormat class or other libraries like JODA are responsible of keeping track of timezone when they transform the date to string.
The date itself doesn't have any time zone. Its toString() method uses the current default time zone to return a String representing this date, as explained in this post. However, you can precise the target timezone during the formatting, to obtain the desired result:
// 2001-01-01T00:00:00.000+00:00
long timestamp = 978307200_000L;
Date newDate = new Date(timestamp);
SimpleDateFormat u = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
u.setTimeZone(TimeZone.getTimeZone("UTC"));
SimpleDateFormat k = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
k.setTimeZone(TimeZone.getTimeZone("Pacific/Kiritimati"));
assertEquals("2001-01-01T00:00:00.000+0000", u.format(newDate));
assertEquals("2001-01-01T14:00:00.000+1400", k.format(newDate));
Well, the only way that I can acquire desired result, is making an adjust to Java Date, I get the current offset of Tomcat and add/remove him from the Date, the follow function make the date returned by rest is allways the same, independent of the tomcat timezone. I use JODA DateTime for this.
public Date adjustDateTimeZoneToUTC( Date date )
{
Date utcDate = null;
if( date != null )
{
int curOffset = TimeZone.getDefault().getRawOffset();
DateTime dt = new DateTime(date).withZoneRetainFields(DateTimeZone.UTC);
// Se o offset for NEGATIVO(-12:00), deve-se somar esse tempo
// Se o offset for POSITIVO(+12:00), deve-se subtrair esse tempo
if( curOffset >= 0 ) {
dt.minusMillis(curOffset);
} else {
curOffset *= -1;
dt.plusMillis(curOffset);
}
utcDate = dt.toDate();
}
return utcDate;
}
On the client side, using angular datepicker or other javascript calendar, you need to do the same way on javascript, for you date stay imutable on different timezones. Like the sample:
$dateParser.timezoneOffsetAdjust = function (date, timezone, undo) {
if (!date) {
return null;
}
// Right now, only 'UTC' is supported.
if (timezone && timezone === 'UTC') {
date = new Date(date.getTime());
date.setMinutes(date.getMinutes() + (undo ? -1 : 1) * date.getTimezoneOffset());
}
return date;
};

How do I format a java.sql.date into this format: "MM-dd-yyyy"?

I need to get a java.sql.date in the following format "MM-dd-yyyy", but I need it to stay a java.sql.date so I can put it into a table as date field. So, it cannot be a String after the formatting, it has to end up as a java.sql.date object.
This is what I have tried so far:
java.util.Date
today=new Date();
String date = formatter.format(today);
Date todaydate = formatter.parse(date);
java.sql.Date fromdate = new java.sql.Date(todaydate.getTime());
java.sql.Date todate=new java.sql.Date(todaydate.getTime());
String tempfromdate=formatter.format(fromdate);
String temptodate=formatter.format(todate);
java.sql.Date fromdate1=(java.sql.Date) formatter.parse(tempfromdate);
java.sql.Date todate1=(java.sql.Date) formatter.parse(temptodate);
You can do it the same way as a java.util.Date (since java.sql.Date is a sub-class of java.util.Date) with a SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat(
"MM-dd-yyyy");
int year = 2014;
int month = 10;
int day = 31;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1); // <-- months start
// at 0.
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
Output is the expected
10-31-2014
Use below code i have convert today date. learn from it and try with your code
Date today = new Date();
//If you print Date, you will get un formatted output
System.out.println("Today is : " + today);
//formatting date in Java using SimpleDateFormat
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM-dd-yyyy");
String date = DATE_FORMAT.format(today);
System.out.println("Today in MM-dd-yyyy format : " + date);
Date date1 = formatter.parse(date);
System.out.println(date1);
System.out.println(formatter.format(date1));
A simpler solution would be to just convert the date in the query to epoch before comparing.
SELECT date_column from YourTable where UNIX_TIMESTAMP(date_column) > ?;
Then, simply pass date.getTime() when binding value to ?.
NOTE: The UNIX_TIMESTAMP function is for MySQL. You'll find such functions for other databases too.
java.util.Date today=new Date();
java.sql.Date date=new java.sql.Date(today.getTime()); //your SQL date object
SimpleDateFormat simpDate = new SimpleDateFormat("MM-dd-yyyy");
System.out.println(simpDate.format(date)); //output String in MM-dd-yyyy
Note that it does not matter if your date is in format mm-dd-yyyy or any other format, when you compare date (java.sql.Date or java.util.Date) they will always be compared in form of the dates they represent. The format of date is just a way of setting or getting date in desired format.
The formatter.parse will only give you a java.util.Date not a java.sql.Date
once you have a java.util.Date you can convert it to a java.sql.Date by doing
java.sql.Date sqlDate = new java.sql.Date (normalDate.getTime ());
Also note that no dates have any built in format, it is in reality a class built on top of a number.
For anyone reading this in 2017 or later, the modern solution uses LocalDate from java.time, the modern Java date and time API, instead of java.sql.Date. The latter is long outdated.
Formatting your date
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-uuuu", Locale.US);
LocalDate fromDate = LocalDate.now(ZoneId.of("Asia/Kolkata"));
String tempFromDate = fromDate.format(formatter);
System.out.println(tempFromDate);
This prints something like
11-25-2017
Don’t confuse your date value with its textual representation
Neither a LocalDate nor a java.sql.Date object has any inherent format. So please try — and try hard if necessary — to keep the two concepts apart, the date on one side and its presentation to a user on the other.
It’s like int and all other data types. An int can have a value of 4284. You may format this into 4,284 or 4 284, 004284 or even into hex representation. This does in no way alter the int itself. In the same way, formatting your date does not affect your date object. So use the string for presenting to the user, and use LocalDate for storing into your database (a modern JDBC driver or other modern means of database access wil be happy to do that, for example through PreparedStatement.setObject()).
Use explicit time zone
Getting today’s date is a time zone sensitive operation since it is not the same date in all time zones of the world. I strongly recommend you make this fact explicit in the code. In my snippet I have used Asia/Kolkata time zone, please substitute your desired time zone. You may use ZoneId.systemDefault() for your JVM’s time zone setting, but please be aware that this setting may be changed under our feet by other parts of your program or other programs running in the same JVM, so this is fragile.

Calendar date to yyyy-MM-dd format in java

How to convert calendar date to yyyy-MM-dd format.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);
Date inActiveDate = null;
try {
inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.
A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.
When you use something like System.out.println(date), Java uses Date.toString() to print the contents.
The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).
Java 8+
LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"
String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12
Prior to Java 8
You should be making use of the ThreeTen Backport
The following is maintained for historical purposes (as the original answer)
What you can do, is format the date.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"
System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"
These are actually the same date, represented differently.
Your code is wrong. No point of parsing date and keep that as Date object.
You can format the calender date object when you want to display and keep that as a string.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String inActiveDate = null;
try {
inActiveDate = format1.format(date);
System.out.println(inActiveDate );
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
java.time
The answer by MadProgrammer is correct, especially the tip about Joda-Time. The successor to Joda-Time is now built into Java 8 as the new java.time package. Here's example code in Java 8.
When working with date-time (as opposed to local date), the time zone in critical. The day-of-month depends on the time zone. For example, the India time zone is +05:30 (five and a half hours ahead of UTC), while France is only one hour ahead. So a moment in a new day in India has one date while the same moment in France has “yesterday’s” date. Creating string output lacking any time zone or offset information is creating ambiguity. You asked for YYYY-MM-DD output so I provided, but I don't recommend it. Instead of ISO_LOCAL_DATE I would have used ISO_DATE to get this output: 2014-02-25+05:30
ZoneId zoneId = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zonedDateTime = ZonedDateTime.now( zoneId );
DateTimeFormatter formatterOutput = DateTimeFormatter.ISO_LOCAL_DATE; // Caution: The "LOCAL" part means we are losing time zone information, creating ambiguity.
String output = formatterOutput.format( zonedDateTime );
Dump to console…
System.out.println( "zonedDateTime: " + zonedDateTime );
System.out.println( "output: " + output );
When run…
zonedDateTime: 2014-02-25T14:22:20.919+05:30[Asia/Kolkata]
output: 2014-02-25
Joda-Time
Similar code using the Joda-Time library, the precursor to java.time.
DateTimeZone zone = new DateTimeZone( "Asia/Kolkata" );
DateTime dateTime = DateTime.now( zone );
DateTimeFormatter formatter = ISODateTimeFormat.date();
String output = formatter.print( dateTime );
ISO 8601
By the way, that format of your input string is a standard format, one of several handy date-time string formats defined by ISO 8601.
Both Joda-Time and java.time use ISO 8601 formats by default when parsing and generating string representations of various date-time values.
java.util.Date object can't represent date in custom format instead you've to use SimpleDateFormat.format method that returns string.
String myString=format1.format(date);
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(year, month, date);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy MM dd");
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
}
In order to parse a java.util.Date object you have to convert it to String first using your own format.
inActiveDate = format1.parse( format1.format(date) );
But I believe you are being redundant here.
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 7);
Date date = c.getTime();
SimpleDateFormat ft = new SimpleDateFormat("MM-dd-YYYY");
JOptionPane.showMessageDialog(null, ft.format(date));
This will display your date + 7 days in month, day and year format in a JOption window pane.
public static String ThisWeekStartDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Before Start Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("Start Date " + CurrentDate);
return CurrentDate;
}
public static String ThisWeekEndDate(WebDriver driver) {
Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Before End Date " + c.getTime());
Date date = c.getTime();
SimpleDateFormat dfDate = new SimpleDateFormat("dd MMM yyyy hh.mm a");
String CurrentDate = dfDate.format(date);
System.out.println("End Date " + CurrentDate);
return CurrentDate;
}
I found this code where date is compared in a format to compare with date field in database...may be this might be helpful to you...
When you convert the string to date using simpledateformat, it is hard to compare with the Date field in mysql databases.
So convert the java string date in the format using select STR_to_DATE('yourdate','%m/%d/%Y') --> in this format, then you will get the exact date format of mysql date field.
http://javainfinite.com/java/java-convert-string-to-date-and-compare/
My answer is for kotlin language.
You can use SimpleDateFormat to achieve the result:
val date = Date(timeInSec)
val formattedDate = SimpleDateFormat("yyyy-MM-dd", Locale("IN")).format(date)
for details click here.
OR
Use Calendar to do it for you:
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val date = "${calendarInstance.get(Calendar.YEAR)}-${calendarInstance.get(Calendar.MONTH)}-${calendarInstance.get(Calendar.DATE)}"
For more details check this answer.
I don't know about y'all, but I always want this stuff as a one-liner. The other answers are fine and dandy and work great, but here is it condensed to a single line. Now you can hold less lines of code in your mind :-).
Here is the one Liner:
String currentDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

Java program to get the current date without timestamp

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);
}
}

Categories

Resources