Hello I am trying to get the current date at java at a Class I created but everything fails. I've seen in many sites
e.g. http://www.mkyong.com/java/java-date-and-calendar-examples/
that the date constructor has no arguments
e.g. Date date = new Date();
Now in my project I try to use it like this and I get the error
that The constructor Date() is undefined
How is this possible? I give you the full code so far
import java.sql.Date;
import java.text.SimpleDateFormat;
public class Utility {
String title;
int ID;
Date date;
Utility(String t,int ID){
this.ID=ID+1;
title=t;
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
Date a=new Date();// I get the error here
String date = sdf.format(a);
System.out.print(date);
}
}
I work at Eclipse IDE. Can you help me?
The examples you found are for java.util.Date while you are using java.sql.Date
java.sql.Date
has two constructors
Date(long date): Constructs a Date object using the given milliseconds time value.
Date(int year, int month, int day): which is deprecated
and no default Date() constructor.
java.util.Date
among others has a default constructor without arguments
Date(): Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
When importing classes, Eclipse will help you fining possible candidates but always check if the first suggestion is really what you want.
You are using the wrong Date class.
Have a look at your imports. Don't use java.sql.Date use java.util.Date instead.
You are importing java.sql.Date use java.util.Date
You have imported wrong class. It is java.util.Date and not java.sql.Date
You can also use use java.util.Calendar as follows:
Calendar c = Calendar.getInstance();
java.util.Date date = c.getTime();
tl;dr
Get today’s date:
LocalDate.now()
Generate text representing today’s date, in your desired format:
LocalDate
.now()
.format(
DateTimeFormatter.ofPattern( "d/M/uuuu" )
)
23/1/2019
Details
The answer by Matteo is correct. You are abusing the java.sql.Date class by treating it as java.util.Date.
But the answers suggesting using java.util.Calendar questions are misguided. Both java.util.Date & Calendar are notoriously bad classes, with poor design and implementation. They are outmoded by the modern java.time.* JSR 310 classes.
Also, when working with date-time you should always think about time zone. Otherwise you'll be getting default time zone with possibly varying behavior at runtime.
java.time
ZonedDateTime zonedDateTime = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
If you want a date-only value, without a time-of-day and without a time zone, use LocalDate.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
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.
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.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am living in Austria and if I print the date in Java I get in the german format. But I want to have it in the english format.
I already tried it with the following code.
import java.util.Date;
import java.text.*;
public class Calendar extends JFrame {
public static void main(String[] args) {
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy", Locale.UK);
System.out.println(dateFormat.format(currentDate));
tl;dr
Never use Date & SimpleDateFormat. Supplanted years ago by java.time classes.
Time zone is crucial to determining current date.
Let DateTimeFormatter.ofLocalized… automatically localize.
LocalDate
.now(
ZoneId.of( "Europe/Vienna )
)
.format(
DateTimeFormatter
.ofLocalizedDate( FormatStyle.FULL )
.withLocale( Locale.UK )
)
Wednesday, 15 May 2019
java.time
The modern approach uses the java.time classes defined in JSR 310.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
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 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.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.
LocalDate localDate = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Localize
The DateTimeFormatter.ofLocalize… methods will automatically localize for you, choosing the appropriate format as well as translating name of day-of-week & month etc.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.UK ; // Or Locale.CANADA_FRENCH, Locale.JAPAN, etc.
DateTimeFormatter f =
DateTimeFormatter
.ofLocalizedDate( FormatStyle.LONG )
.withLocale( l )
;
String output = localDate.format( f );
output: Wednesday, 15 May 2019
Alternatively, define your own custom formatting pattern using DateTimeFormatter.ofPattern. Pass the optional Locale argument, to determine localization. Search Stack Overflow, as this has been covered many times. And see this other Answer on this page by Gaurav Shakya.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Use This: Java 8
LocalDate localDate=LocalDate.now();
String dateInGerman=localDate.format(DateTimeFormatter.ofPattern("EEEE, dd MMMM, yyyy",Locale.GERMANY));
If anyone is interested:
The code runs now. I have just imported "java.util.Locale"
Nevertheless thanks for you help
So, I started to test around a bit with the Java-GregorianCalendar Class and noted a weird behaviour occuring, when initializing the Object with milliseconds. What bothered me was, although I set the milliseconds to 0 the time showed 1 o'clock.
After browsing StackOverflow a bit I noticed that Java sometimes gets confused with summer and winter time. So my question is, if although the time change was already done this year and we live in winter time again, this weird behaviour comes from winter and summertime.
Here is the Code I was testing around with:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class TestCalendar {
public static void main(String[] args) {
GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(-3600000);
System.out.println(c.getTimeInMillis());
System.out.println(c.get(Calendar.HOUR));
String format = "mm:ss";
if (c.get(Calendar.HOUR_OF_DAY) > 0) format = "HH:mm:ss";
System.out.println(new SimpleDateFormat(format).format(c.getTime()));
}
}
This gave me the Output
-3600000
0
0
The best thing would be to find a solution which is independent from substracting -3600000 as if on other computers this "bug" does not exist I dont want to have 23:00:00 :)
EDIT:
After trying a bit more out and thanks to the Feedback I was able to fix my little problem by just adding this line just after initializing the Calendar:
c.setTimeZone(TimeZone.getTimeZone("GMT"));
tl;dr
Problem: You are mistakenly changing the date, not just the time-of-day. On top of that, a time zone is implicitly being applied.
Solution: Instead use the modern java.time classes.
LocalDate
.now() // Better to explicitly pass the desired/expected time zone as a `ZoneId` object.
.atStartOfDay() // Again, better to explicitly pass the desired/expected time zone as a `ZoneId` object.
Returns a LocalDateTime (BEWARE: Not a moment, not a point on the timeline).
2018-11-01T00:00
Much better to specify time zone.
LocalDate
.now(
ZoneId.of( "Pacific/Auckland" )
)
.atStartOfDay(
ZoneId.of( "Pacific/Auckland" )
)
Returns a ZonedDateTime. This is a moment, is a point on the timeline.
2018-11-02T00:00+13:00[Pacific/Auckland]
GregorianCalendar::setTimeInMillis is not setting time-of-day
Apparently you mistakenly thought the GregorianCalendar::setTimeInMillis would set the time-of-day without affecting the date. Among the many flaws in these legacy date-time classes is some very poor choices in naming classes and methods.
But, no, that method redefines the moment as a count of milliseconds since epoch reference date of 1970-01-01T00:00Z.
Add in the time zone implicitly assigned to GregorianCalendar, and you have unexpected results.
I started to test around a bit with the Java-GregorianCalendar
Don’t.
Those old date-time classes bundled with the earliest versions of Java are terrible. They were supplanted years ago by the java.time classes defined in JSR 310.
Specifically, to track a moment in UTC, use Instant.
initializing the Object with milliseconds
Don’t.
Tracking time as a count-from-epoch-reference is prone to error. There are many different epoch reference dates in use in the industry. There are different granularities in use in the industry (whole seconds, milliseconds, microseconds, nanoseconds).
So a count-from-epoch is ambiguous. Also prone to confusing and missed errors because humans cannot read the meaning of the values.
When exchanging date-time values, use strings in standard ISO 8601 format instead.
When handed a count of milliseconds from the Unix epoch of first moment of 1970 in UTC, parse as an Instant.
Instant instant = Instant.ofEpochMilli( … ) ;
java.time
The modern solution uses java.time classes instead.
Get your date.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
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.
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 JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
ZonedDateTime
Apparently you want the first moment of the day. By the way, do not think of this as “midnight” as that term is ambiguous.
The first moment of the day may not be 00:00. Anomalies such as Daylight Saving Time (DST) mean that the first moment on some dates in some zones may be another time such as 01:00. Let java.time determine the first moment.
Specify a time zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = localDate.atStartOfDay( z ) ;
If you want to see that same moment in UTC, extract a Instant.
Instant instant = zdt.toInstant() ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Setting c.setTimeInMillis(0); sets the time to January 1, 1970 at 00:00:00 GMT (1970-01-01 00:00:00 GMT) which is called the epoch
https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeInMillis(long)
public void setTimeInMillis(long millis)
Sets this Calendar's current time from the given long value.
Parameters:
millis - the new time in UTC milliseconds from the epoch.
See Also:
setTime(Date), getTimeInMillis()
If you want to set the time to midnight, I think you want to do.
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
I have one date and i have to check whether it was saturday or sunday. Am i proceeding right way ??
Calendar gcal = new GregorianCalendar();
DateFormat dateFormat = new SimpleDateFormat("EEEE");
Date currentDate = gcal.getTime();
String strDate = dateFormat.format(currentDate);
if (!"Saturday".equals(strDate)) {
}
its working fine. but i cant compare two string like,
if (!"Saturday" || "Sunday".equals(strDate)) {}
If a date was Saturday or sunday i have to skip the loop....
Thanks in advance...
No need to create/format a Date object, use Calendar methods:
Calendar gcal = new GregorianCalendar();
if (gcal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && gcal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
}
If a date was Saturday or sunday i have to skip the loop.
Then it should be
if (!("Saturday".equals(strDate) || "Sunday".equals(strDate)) {
}
tl;dr
Is today a Saturday?
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.getDayOfWeek()
.equals( DayOfWeek.SATURDAY )
Details
Am i proceeding right way ??
No. You are using the troublesome old date-time classes that have been supplanted by the java.time classes.
Another problem is relying implicitly on default time zone. Better to specify your intended time zone explicitly. Time zone determines the date, and date determines the day-of-week, so time zone is crucial.
And another problem is that you are needlessly converting from a Calendar to a Date. But better to avoid these classes entirely.
DayOfWeek
The DayOfWeek enum defines seven objects, one for each day of the week.
You should be passing these objects around your code rather than a string. Notice in the code below that we do not use strings at all.
Be clear that these DayOfWeek objects are not strings. They are real objects, offering several methods. Those methods include toString that generates a hard-coded String in English, all in uppercase. The method getDisplayName generates the name of the day-of-week automatically localized in various human languages.
Enums in Java are much more powerful and practical than conventionally seen in other languages. See Oracle Tutorial.
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.
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 );
today.toString(): 2017-02-27
Interrogate the LocalDate object for its DayOfWeek.
DayOfWeek dow = today.getDayOfWeek();
dow.toString(): MONDAY
Compare to your target day-of-week.
Boolean isTodaySaturday = dow.equals( DayOfWeek.SATURDAY );
isTodaySaturday.toString(): false
Try this code live at IdeOne.com.
See similar Question: How to skip weekends while adding days to LocalDate in Java 8?
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 and 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 SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Alternatively:
if (!strDate.matches("Saturday|Sunday")) {
}
But it is slower.
I need to get the last date of a given month, in my case I need to get the last Date of June. My code is following:
cal.set(Calendar.DAY_OF_MONTH,
Calendar.getInstance().getActualMinimum(Calendar.DAY_OF_MONTH));
int month = cal.get(Calendar.MONTH) + 1;
if (month <= 6) {
cal.set(Calendar.DAY_OF_YEAR, Calendar.getInstance()
.getActualMaximum(Calendar.JUNE));
return (Calendar) cal;
} else {
cal.set(Calendar.DAY_OF_YEAR, Calendar.getInstance()
.getActualMaximum(Calendar.DAY_OF_YEAR));
return (Calendar) cal;
}
At first I get the actual month and wether it's the first half of the year or the second in need another date, always the last date of that half year. With the code above the return is
2015-01-31
and not 2015-06-31 as I thought it should be. How could I possibly fix this?
Your code is all over the place at the moment, unfortunately - you're creating new calendars multiple times for no obvious reason, and you're calling Calendar.getActualMaximum passing in the wrong kind of constant (a value rather than a field).
You want something like:
int month = cal.get(Calendar.MONTH) <= Calendar.JUNE
? Calendar.JUNE : Calendar.DECEMBER;
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calenday.DAY_OF_MONTH));
return cal;
However, I would strongly recommend using java.time if you're on Java 8, and Joda Time if you're not - both are much, much better APIs than java.util.Calendar.
java.time
Much easier now with the modern java.time classes. Specifically, the YearMonth, Month, and LocalDate 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 ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
YearMonth
With a LocalDate in hand, get the year-month of that date.
YearMonth ym = YearMonth.from( ld ) ;
See which half year it is in.
Set < Month > firstHalfOfYear = EnumSet.range( Month.JANUARY , Month.JUNE ); // Populate the set with first six months of the year.
boolean isFirstHalf = firstHalfOfYear.contains( ym.getMonth() );
Knowing which half of the year, get the end of June or the end of December in the same year.
LocalDate result = null;
if ( isFirstHalf ) {
result = ym.withMonth( Month.JUNE.getValue() ).atEndOfMonth();
} else { // Else in last half of year.
result = ym.withMonth( Month.DECEMBER.getValue() ).atEndOfMonth();
}
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I'd love your help understanding the following:
Assume that I have a Value of type date
Date start;
How can I chack whether the current date is a week or more since the date of start ?
I tried to chack Java API on the web, and I got confused.
Thank you.
Using calendar you can add days to the start date and then compare it to the current date.
For example:
Date start = Calendar.getInstance().getTime();
start.setTime(1304805094L); // right now...
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_YEAR, 7);
start.compareTo(cal.getTime());
I would use Joda time for that.
http://joda-time.sourceforge.net/
You can then use this method as a template for what you want to do. The method is an example from the Joda site:
public boolean isRentalOverdue(DateTime datetimeRented) {
Period rentalPeriod = new Period().withDays(2).withHours(12);
return datetimeRented.plus(rentalPeriod).isBeforeNow();
}
tl;dr
whether the current date is a week or more since the date of start ?
LocalDate.now().minusWeeks( 1 ).isAfter( someLocalDate )
java.time
The modern approach uses java.time classes.
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 );
Specify the other date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
So, is the current date at least a week after the target date?
Calculate a week ago.
LocalDate weekAgo = today.minusWeeks( 1 ) ;
Compare with isBefore, isAfter, and isEqual methods.
Boolean isOverAWeekOld = ld.isBefore( weekAgo ) ;
Bonus: See if the target date is within the past week.
boolean inPastWeek = ( ! ld.isBefore( weekAgo ) ) && ld.isBefore( today ) ;
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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.