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
Related
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 am trying to get a list of dates in scala
val savePoint:java.util.Date= //olderDate
var days = List[String]()
for (date<-savePoint to java.util.Date.parse("yyyy-MM-dd") by date.plusDays(1)){
days::=date
}
but getting error
value to is not a member of java.util.Date
tl;dr
Using java.time.LocalDate, produce a stream by calling datesUntil, collected into a List.
In Java syntax (I don't know Scala):
LocalDate // Represent a date-only value, without time-of-day, and without offset-from-UTC or time zone.
.of( 2019 , Month.SEPTEMBER , 22 ) // Specify you date in the past.
.dateUntil( // Generate a Stream of LocalDate objects.
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Capture the current date as seen through the wall-clock time used by the people of a particular region (a time zone).
) // Returns a `Stream< LocalDate >`.
.collect ( // Collects the items provided by the stream.
Collectors.toUnmodifiableList () // Instantiates an unmodifiable `List` of some indeterminate concrete class.
) // Returns a `List` holding `LocalDate` objects.
.toString() // Generates a textual listing of the collected dates using standard ISO 8601 format.
[2019-09-22, 2019-09-23, 2019-09-24, 2019-09-25, 2019-09-26, 2019-09-27, 2019-09-28, 2019-09-29, 2019-09-30, 2019-10-01, 2019-10-02, 2019-10-03]
java.time
The modern solution uses the java.time classes, specifically 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. 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.
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 ) ;
LocalDate::datesUntil ➙ Stream of LocalDate objects
You can accomplish your goal in a one-liner, by calling LocalDate::datesUntil to generate a stream that can be collected into a list.
ZoneId z = ZoneId.of ( "America/Edmonton" );
LocalDate today = LocalDate.now ( z );
LocalDate then = LocalDate.of ( 2019 , Month.SEPTEMBER , 22 );
List < LocalDate > dates = then.datesUntil ( today ).collect ( Collectors.toUnmodifiableList () );
Dump to console.
System.out.println ( "From: " + then + " to: " + today + " is: " + dates );
From: 2019-09-22 to: 2019-10-04 is: [2019-09-22, 2019-09-23, 2019-09-24, 2019-09-25, 2019-09-26, 2019-09-27, 2019-09-28, 2019-09-29, 2019-09-30, 2019-10-01, 2019-10-02, 2019-10-03]
org.threeten.extra.LocalDateRange
FYI, to represent a span-of-time between a pair of dates, you can use the LocalDateRange class from the ThreeTen-Extra project.
LocalDateRange range = LocalDateRange.of( then , 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.
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.
For Scala, you can use Lamma Date (http://www.lamma.io)
Welcome to Scala version 2.11.6 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_71).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import io.lamma._
import io.lamma._
scala> Date(2015, 7, 1) to Date.today() foreach println
Date(2015,7,1)
Date(2015,7,2)
Date(2015,7,3)
Date(2015,7,4)
Date(2015,7,5)
Date(2015,7,6)
Date(2015,7,7)
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.
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.
At the moment, I'm creating a java schedule app and I was wondering how to find the current day of the week while using the Calendar class to get the first day of the week.
Here is the method I'm using in a class in order to set up a week schedule
public static String getSunday() {
SimpleDateFormat d = new SimpleDateFormat(dayDate);
Calendar specific = cal;
specific.add(Calendar.DAY_OF_YEAR, (cal.getFirstDayOfWeek() - ??));
return d.format(specific.getTime());
}
You can get the current day of the week by calling get() with Calendar.DAY_OF_WEEK
public int getTodaysDayOfWeek() {
final Calendar c = Calendar.getInstance();
return c.get(Calendar.DAY_OF_WEEK);
}
Also, while I'm not sure I understand exactly what you're trying to do, it looks fishy to me. (What's cal for example?)
tl;dr
how to find the current day of the week
DayOfWeek.from( LocalDate.now() )
set up a week schedule
LocalDate sunday =
LocalDate.now()
.with( TemporalAdjusters.nextOrSame( DayOfWeek.SUNDAY ) ) ;
LocalDate monday = sunday.plusDays( 1 ) ;
LocalDate tuesday = monday.plusDays( 1 ) ;
…
Details
The Question and other Answer both use outmoded classes.
The old date-time classes are poorly designed, confusing, and troublesome. Avoid them.
java.time
In Java 8 and later, we use the built-in java.time framework. Much of the functionality is back-ported to Java 6 & 7 (ThreeTen-Backport), and further adapted to Android (ThreeTenABP).
An Instant represents the current moment in UTC with a resolution up to nanoseconds.
Instant instant = Instant.now();
To get the day-of-week we must determine the date. Time zone is crucial in determining the date as the date can vary around the globe for any given moment. For example, a few minutes after midnight in Paris is a new day, while in Montréal it is still “yesterday”.
Use ZoneId to represent a time zone. Ask for a proper time zone name in format of continent/region. Never use the 3-4 letter abbreviations commonly seen in mainstream media as they are not true time zones, not standardized, and are not even unique(!).
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Use the handy DayOfWeek enum to determine the day of the week.
DayOfWeek dow = DayOfWeek.from( zdt );
You may interrogate the DayOfWeek object.
You may ask for a number from 1 to 7 where 1 is Monday and 7 is Sunday per the ISO 8601 standard. But do not pass this number around your code; instead pass around DayOfWeek objects to enjoy the benefits of type-safety and guaranteed valid values.
int dowNumber = dow.getValue();
You may want text, the name of the day of the week. Let java.time automatically translate the name into a human language. A Locale species which human language, and also specifies the cultural norms to use such as how to abbreviate and capitalize. The TextStyle enum indicates how long a name you want.
Locale locale = Locale.CANADA_FRENCH;
String output = dow.getDisplayName( TextStyle.FULL , locale );
To get the start of the week, ask for the previous Monday (or Sunday, whatever), or stick with today if it is a Monday. Use a TemporalAdjuster implementation found in TemporalAdjusters class.
LocalDate startOfWeek = zdt.toLocalDate().with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) );
If you need a date-time rather than date-only, ask java.time to get the first moment of the day (not always the time 00:00:00).
ZonedDateTime zdtWeekStart = startOfWeek.atStartOfDay( zoneId );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.