setting and getting time from Date in java - java

I have a Date . I want to copy its time only, excluding the date. I then need to insert the time into another date.
Is there a easy way to do this?. I cant change the Date datatype. I can do, getHour(),getMinutes() etc however this is long winded. is there a clearner version that i could use ? or perhaps other library's like apache commons to set/get date time (have not spotten anything so far).

Try this:
public static Date copyTimeOnly(Date toDate, Date fromDate) {
Calendar toCal = new GregorianCalendar();
toCal.setTime(toDate);
Calendar fromCal = new GregorianCalendar();
fromCal.setTime(fromDate);
// Copy time only
toCal.set(Calendar.HOUR_OF_DAY, fromCal.get(Calendar.HOUR_OF_DAY));
toCal.set(Calendar.MINUTE, fromCal.get(Calendar.MINUTE));
toCal.set(Calendar.SECOND, fromCal.get(Calendar.SECOND));
toCal.set(Calendar.MILLISECOND, fromCal.get(Calendar.MILLISECOND));
return toCal.getTime();
}

If you just need the time part of your Date object and you can't use Java 8 and don't want to use any third party framework, then use Calendar:
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
c.set(Calendar.YEAR, 0);
c.set(Calendar.MONTH, 0);
c.set(Calendar.DAY, 0);
Date timeOnly = c.getTime();

or if you can use third party libraries(in this case org.apache.commons.lang3.time)
you could do it this way:
private Date truncate(Date pDate) {
return DateUtils.truncate(pDate, Calendar.DATE);
}

LocalTime
The old java.util.Date/.Calendar have no class to represent a time-of-day value without a date portion. In contrast, both the Joda-Time library and the new java.time package built into Java 8 (inspired by Joda-Time) offer a LocalTime class.
Joda-Time
Here is example code using Joda-Time 2.5.
Time zone is crucial. Do you want the time of day for that moment as seen by someone in Paris, Montréal, or Kolkata?
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime = new DateTime( yourJUDate, zone );
LocalTime localTime = dateTime.toLocalTime();
To apply that LocalTime to another DateTime, call withTime. Joda-Time uses immutable objects. So a new DateTime object is created with values based on the original.

Related

How to compare "now" and a future time

I need to compare the time a local file was downloaded with a time in the future/past to see if the file needs to be re-downloaded to update it. I can get the time the local file was last downloaded with :
long timeSinceCreateFile = myFile.lastModified();
What I need is to check timeSinceCreateFile with a time that is the NEXT Friday at 21:30hs and if the current time: System.currentTimeMillis()
is in the future to this then re-download the file.
I've read heaps on Calendar, Time, Date, Joda-Time etc. but have not been able to figure out how to get a moment in time as a specific Day, Hour, Minuet, etc. that is RELATIVE to timeSinceCreateFile
Edit
I need to know the time in milliseconds between when a file was downloaded (or last modified) long timeSinceCreateFile = myFile.lastModified(); and the FOLLOWING Friday at 21:30hs (as in the Friday at 21:30hrs AFTER timeSinceCreateFile)
I can then compare the "FOLLOWING FRIDAY AT 21:30hrs" milliseconds to the current time 'System.currentTimeMillis()` and if one is greater than the other re-download the file.
Hope this clarified my question, if not let me know because I really need help with this.
Thanks.
Your temporal condition "next Friday at 21:30" is hard to realize in standard Java-library using java.util.Calendar and java.util.Date.
In Joda-Time it also requires a non-trivial workaround (again with loop).
In Java-8 (new time library JSR-310 in package java.time) an acceptable solution using specialized methods in TemporalAdjusters is possible, but since you operate on Android, this is not the way to go.
Instead here an alternative solution in my library Time4J which does not need any error-prone loops or complex conditions:
import static net.time4j.PlainDate.DAY_OF_WEEK;
import static net.time4j.Weekday.FRIDAY;
File myFile = new File("");
long timeSinceCreateFile = myFile.lastModified();
// conversion to global timestamp in Time4J-format
Moment fileTSP = TemporalTypes.MILLIS_SINCE_UNIX.transform(timeSinceCreateFile);
// what ever you need (or just TZID timezone = Timezone.ofSystem().getID();)
TZID timezone = AMERICA.MONTREAL;
// "next friday" is a local time condition => convert to local timestamp
PlainTimestamp localTSP = fileTSP.toZonalTimestamp(timezone);
PlainTime walltime2130 = PlainTime.of(21, 30);
// move to next time 21:30 (possibly on next day) and then to next or same Friday
localTSP =
localTSP.with(PlainTime.COMPONENT.setToNext(walltime2130))
.with(DAY_OF_WEEK.setToNextOrSame(FRIDAY));
// convert current time to local timestamp and compare at 21:30
boolean downloadNeeded = SystemClock.inZonalView(timezone).now().isAfter(localTSP);
GregorianCalendar ? set the date to your year, month, day, 21:30, set day of week to friday. Use getTime to get a long millisecs. This will give you a UNIX time for some friday 21:30 close to your date. Keep adding or removing the number of milliseconds in a week until the time minus your file time is in the range [0 number of milliseconds in a week]. Warning with month, it's 0 based.
public static void main(String[] args){
long fileCreateTime = new Date().getTime();
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(new Date(fileCreateTime));
calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
calendar.set(Calendar.HOUR_OF_DAY, 21);
calendar.set(Calendar.MINUTE, 30);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
long MILLISECS_IN_A_WEEK = 7*24*60*60*1000;
long calendarMillisecs = calendar.getTime().getTime();
while(calendarMillisecs<fileCreateTime){
calendarMillisecs += MILLISECS_IN_A_WEEK;
}
while(calendarMillisecs>fileCreateTime+MILLISECS_IN_A_WEEK){
calendarMillisecs -= MILLISECS_IN_A_WEEK;
}
System.out.println(new Date(calendarMillisecs));
}
Ugly, but will work.
Avoid java.util.Date & .Calendar
Avoid java.util.Date and .Calendar because they are notoriously troublesome, flawed, and confusing. Use either Joda-Time or the new java.time package in Java 8.
Joda-Time
In Joda-Time 2.4.
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime start = DateTime.now( timeZone );
// DateTime start = new DateTime( fileLastModifiedMillis, timeZone );
DateTime dateTime = start;
while ( dateTime.getDayOfWeek() != DateTimeConstants.FRIDAY ) {
dateTime = dateTime.plusDays( 1 );
}
To compare…
boolean isLate = oneDateTime.isAfter( someOtherDateTime );

Android how to get tomorrow's date

In my android application. I need to display tomorrow's date, for example today is 5th March so I need to display as 6 March. I know the code for getting today's date, month and year.
date calculating
GregorianCalendar gc = new GregorianCalendar();
yearat = gc.get(Calendar.YEAR);
yearstr = Integer.toString(yearat);
monthat = gc.get(Calendar.MONTH) + 1;
monthstr = Integer.toString(monthat);
dayat = gc.get(Calendar.DAY_OF_MONTH);
daystr = Integer.toString(dayat);
If I have the code
dayat = gc.get(Calendar.DAY_OF_MONTH) + 1;
will it display tomorrow's date. or just add one to today's date? For example, if today is January 31. With the above code, will it display like 1 or 32? If it displays 32, what change I need to make?
Get today's date as a Calendar.
Add 1 day to it.
Format for display purposes.
For example,
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);
// now do something with the calendar
Use the following code to display tomorrow date
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
Use SimpleDateFormat to format the Date as a String:
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
System.out.println(todayAsString);
System.out.println(tomorrowAsString);
Prints:
05-Mar-2014
06-Mar-2014
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
you have to add just 1 in your Calendar Day.
GregorianCalendar gc = new GregorianCalendar();
gc.add(Calendar.DATE, 1);
java.util.Date and java.util.Calendar are terrible to work with. I suggest you use JodaTime which has a much cleaner / nicer API. JodaTime is pretty standard these days.
http://www.joda.org/joda-time/#Why_Joda-Time
Note that JDK 8 will introduce a new date/time API heavily influenced by JodaTime.
http://java.dzone.com/articles/introducing-new-date-and-time
https://jcp.org/en/jsr/detail?id=310
Other options:
Calendar tomorrow = Calendar.getInstance();
tomorrow.roll(Calendar.DATE, true);
or
tomorrow.roll(Calendar.DATE, 1);
roll can also be used to go back in time by passing a negative number, so for example:
Calendar yesterday = Calendar.getInstance();
yesterday.roll(Calendar.DATE, -1);
the first answers pretty much covers the possibilities.
but here one another solution which you can use from org.apache.commons.lang.time:
Date lTomorrow = DateUtils.addDays(new Date(), 1);
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use either Joda-Time library or the new java.time package in bundled with Java 8.
Some example code using the Joda-Time 2.3 library.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( timeZone );
DateTime tomorrow = now.plusDays( 1 );
String output = DateTimeFormat.forPattern( "FF" ).withLocale(Locale.FRANCE).print( tomorrow );
Get todays date by using calendar and then add 1 day to it.
This is working to me well!!
Date currentDate = new Date();// get the current date
currentDate.setDate(currentDate.getDate() + 1);//add one day to the current date
dateView.setText(currentDate.toString().substring(0, 10));// put the string in specific format in my textView
good luck!!
much easier now
String today = LocalDateTime.now().format(DateTimeFormatter.ofPattern("MM-dd"));
String tomorrow = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("MM-dd"));
Try like this..
dayat = gc.add(Calendar.DATE, 1);
tl;dr
java.time.LocalDate.now()
.plusDays( 1 )
java.time
All the other Answers are outmoded, using the troublesome old Date & Calendar classes or the Joda-Time project which is now in maintenance mode. The modern approach uses the java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
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, so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-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 ) ;
From that LocalDate you can do math to get the following day.
LocalDate tomorrow = today.plusDays( 1 ) ;
Strings
To generate a String representing the LocalDate object’s value, call toString for text formatted per the ISO 8601 standard: YYYY-MM-DD.
To generate strings in other formats, search Stack Overflow for DateTimeFormatter.
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
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….
Best way for setting next day is
public void NextDate()
{
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
// set current date into textview
e_date.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(mDay+1).append("-").append(mMonth + 1).append("-")
.append(mYear).append(" "));
}
Just call this method and send date from which you want next date
public String nextDate(Date dateClicked) {
//
String next_day;
calander_view.setCurrentDayTextColor(context.getResources().getColor(R.color.white_color));
//calander_view.setCurrentDayBackgroundColor(context.getResources().getColor(R.color.gray_color));
SimpleDateFormat dateFormatForDisplaying = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
String date_format = dateFormatForDisplaying.format(dateClicked);
SimpleDateFormat simpleDateformat = new SimpleDateFormat("E"); // the day of the week abbreviated
final Calendar calendar = Calendar.getInstance();
try {
Date date = dateFormatForDisplaying.parse(date_format);
calendar.setTime(date);
calendar.add(Calendar.DATE, 1);
String nex = dateFormatForDisplaying.format(calendar.getTime());
Date d1 = dateFormatForDisplaying.parse(nex);
String day_1 = simpleDateformat.format(d1);
next_day = nex + ", " + day_1;
} catch (ParseException e) {
e.printStackTrace();
}
return next_day;
}
String lastDate="5/28/2018";
Calendar calendar = Calendar.getInstance();
String[] sDate=lastDate.split("/");
calendar.set(Integer.parseInt(sDate[2]),Integer.parseInt(sDate[0]),Integer.parseInt(sDate[1]));
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
// String todayAsString = dateFormat.format(today);
for (int i=1;i<29;i++)
{
calendar.add(Calendar.DAY_OF_YEAR,1);
// td[i].setText(dateFormat.format(calendar.getTime()));
System.out.println(dateFormat.format(calendar.getTime()));
}

Joda: Convert Date and Time to DateTime

Is there a way to convert a Time and Date variable to a DateTime?
I have a period between two DateTime variables, for each Date in that period I want to store a period IN that Date with a begin DateTime and end DateTime, so a day can have multiple periods defined by a DateTime.
Can't seem to figure out how to combine Date and Time to a DateTime.
Thanks in advance!
Plain java Date and Joda-Time DateTime should serve the purpose.
Date date = new Date(); // java.util.Date; - This date has both the date and time in it already.
DateTime dateTime = new DateTime(date);
For more info about Joda-Time.
If you have two String objects, where 1 holds the Date and the other Time, you can combine the 2 Strings and use a SDF to parse it and get the Date object, which you can then convert to DateTime.
Fixed it using this:
public DateTime dateAndTimeToDateTime(java.sql.Date date, java.sql.Time time) {
String myDate = date + " " + time;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date utilDate = new java.util.Date();
try {
utilDate = sdf.parse(myDate);
} catch (ParseException pe){
pe.printStackTrace();
}
DateTime dateTime = new DateTime(utilDate);
return dateTime;
}
Even if this question is a bit older and already answered, I could not find a satisfying solution. The best method for this problem is probably the following code (without any parsing and exception handling required):
public DateTime dateAndTimeToDateTime(java.sql.Date date, java.sql.Time time) {
DateTime t = new DateTime(time);
return new DateTime(date).withTime(t.getHourOfDay(), t.getMinuteOfHour(), t.getSecondOfMinute(), t.getMillisOfSecond());
}
I am pretty sure that you can find how to construct date and time instances separately.
However on the datetime object itself you can specify the following.
dateTimeObject = dateTimeObject.withHourOfDay(12);
dateTimeObject = dateTimeObject.withMinuteofHour(59);
dateTimeObject = dateTimeObject.withSecondOfMinute(59);
Hope this helps!
java.time
With java.time, the modern Java date and time API, this is simple and straightforward:
LocalTime time = LocalTime.of(23, 45);
LocalDate date = LocalDate.of(2019, Month.NOVEMBER, 23);
LocalDateTime combined = date.atTime(time);
System.out.println(combined);
Output is:
2019-11-23T23:45
I know you asked about Joda-Time. However, the Joda-Time homepage says:
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time (JSR-310).
Links
Oracle tutorial: Date Time explaining how to use java.time.
Joda-Time homepage
DateTime dateTime = new DateTime("yyyy-MM-dd");.
System.out.println("============> " + dateTime.toString());
INPUT : 2018-01-04
OUTPUT: ============> 2018-01-05T00:00:00.000+05:30

java get the current computer's date

how can i get computer's date on java, i want just year, month, day
i tried to get calender like this
Calendar c =Calendar.getInstance();
c.clear(Calendar.HOUR)
but can't know to deal with it,
First link on google:
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date);
}
Try this ONE line of code.....
// Prints 01-07-2012
System.out.println(new SimpleDateFormat("dd-MM-YYYY").format(new Date()));
// Prints 01-Jul-2012
System.out.println(new SimpleDateFormat("dd-MMM-YYYY").format(new Date()));
Calendar rightNow = Calendar.getInstance();
int y = rightNow.get(Calendar.YEAR);
int m = rightNow.get(Calendar.MONTH) + 1;
int d = rightNow.get(Calendar.DAY_OF_MONTH);
System.out.println("year "+y+" month "+m+" day "+d);
You can obtain the current date as a year/month/day string like this:
String strDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
System.out.println(strDate);
> 2012-07-01
Notice that a Date object will always contain year, month, day, hours, minutes, seconds, milliseconds, etc., and by calling new Date() you obtain a date object with the current time.
If you only need some fields of a date (say, year, month and day) you need to format the date using a formatter, for instance SimpleDateFormat. Check the link for learning more about the string formatting options available in Java.
Joda-Time
Some example code using the Joda-Time 2.4 library.
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8 (inspired by Joda-Time, defined by JSR 310).
Time Zone
Note the use of a time zone. A time zone is necessary to determine a date. The same simultaneous moment in Kolkata and Paris may have different dates on the calendar. If you omit a time zone, the JVM’s current default time zone will be applied. That means your results may vary, so best to explicitly specify the time zone you intend.
Example Code
String output = LocalDate.now( TimeZone.forID( "Asia/Kolkata" ) ).toString();

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