Android: Get year, month, day from GregorianCalendar Object - android

The GregorianCalendar constructor asks for the following:
GregorianCalendar(int year, int month, int dayOfMonth);
How can I extract the year, month, and day from an object I have created. Right now I'm using object.YEAR, object.MONTH, and object.DAY_OF_MONTH, but that does not seem to be giving me the right numbers.
Thanks.
Here I get a date based on which calendar date a user clicks. The user can then enter some information into that date which is stored in a HashMap keyed on GregorianCalendar.
cal.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
selectedDate = new GregorianCalendar(year, month, dayOfMonth);
Here I am trying to write the date from the GregorianCalendar year, month, and day parameters to a file to be used later.
private void writeToFile() {
try
{
PrintWriter writer = new PrintWriter(file, "UTF-8");
for (GregorianCalendar gregObject: recipes.keySet()) {
String[] value = recipes.get(gregObject);
int y = gregObject.YEAR;
int m = gregObject.MONTH;
int d = gregObject.DAY_OF_MONTH;
writer.printf("%d %d %d ", y, m, d);
Here is how I read from the file. When I read from the file I get the numbers 1,2,5 for year, month, and date which is wrong. The rest of the information read is correct.
try
{
Scanner getLine = new Scanner(file);
Scanner tokenizer;
while (getLine.hasNextLine()) {
String line = getLine.nextLine();
tokenizer = new Scanner(line);
System.out.println(line);
while (tokenizer.hasNextInt()) {
int y1 = tokenizer.nextInt();
int m1 = tokenizer.nextInt();
int d1 = tokenizer.nextInt();
Obviously I think I am writing the year, month, and day wrongly to the file, so I'm trying to figure out the correct way to extract the year, month, and day from a GregorianCalendar object.

Hope following helps: I am using 2015/06/10 as input. Please note month values are 0 (Jan) - 11 (Dec).
package demo;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* Create on 4/3/16.
*/
public class TestCalendar {
public static void main(String [] args){
Calendar cal = new GregorianCalendar(2015,05,10); // Month values are 0(Jan) - 11 (Dec). So for June it is 05
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); // 0 - 11
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
// Following must output 2015/06/10
System.out.printf("Provided date is %4d/%02d/%02d", year, month+1, dayOfMonth);
}
}

tl;dr
You are working too hard.
You are using troublesome old date-time classes now supplanted by the modern java.time classes.
Example:
LocalDate.now().getYear() // Better to pass a specific time zone (`ZoneId`) as optional argument: LocalDate.now( ZoneId.of( "Africa/Tunis" ) ).getYear()
2018
java.time
Do not use a date-time class if you really only care about the date without the time.
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 ) ;
year-month-day parts
Interrogate for the parts, as needed.
int ld.getYear() ;
int ld.getMonthValue() ;
int ld.getDayOfMonth() ;
Legacy code
If you must inter-operate with old code not yet converted to java.time, you may convert using new methods added to the old classes.
The equivalent of GregorianCalendar is ZonedDateTime.
ZonedDateTime zdt = myGregCal.toZonedDateTime() ; // Convert from legacy class to modern class.
Interrogate for the parts, as needed.
int zdt.getYear() ;
int zdt.getMonthValue() ;
int zdt.getDayOfMonth() ;
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.

Related

check if saved date is one day before to current date android

Okay so i read this : Check date with todays date
#sudocode gave this code :
Calendar c = Calendar.getInstance();
// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
// and get that as a Date
Date today = c.getTime();
// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();
// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;
// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
// and get that as a Date
Date dateSpecified = c.getTime();
// test your condition
if (dateSpecified.before(today)) {
System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}
But imagine the saved date was 28/01/2018 11:00pm and i run this at 28/01/2018 11:15pm so this code will tell me that saved date is before the current date.
What i want is, the code should only run a function if the saved date is more than one day old... (not 24 hours but actually a day or more old) lets say saved date it 27/01/2018 11:00pm and current date is 28/01/2018 then it should run.. how do i implement this ?
You can do something like this:
public long daysBetween(Calendar first, Calendar second) {
long diffInMillis = second.getTimeInMillis() - first.getTimeInMillis();
return TimeUnit.MILLISECONDS.toDays(diffInMillis);
}
And then just ask if the difference is >= 1. This also assumes that second >= first.
This example is using the standard Java (7) date stuff, so you should be able to use it in your project.
tl;dr
Determining dates requires a time zone.
Use only java.time classes, never legacy java.util.Date, Calendar, java.sql.Date, java.sql.Timestamp, etc.
myResultSet.getObject(
… ,
Instant.class
) // Retrieve a `java.time.Instant` from a column of type akin to the SQL-standard `TIMESTAMP WITH TIME ZONE`.
.atZone(
ZoneId.of( "Pacific/Auckland" )
)
.toLocalDate()
.isEqual(
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
)
Avoid legacy date-time classes
The terrible Date and Calendar legacy classes were supplanted years ago by the modern java.time classes.
Time zones
Your Question ignores the crucial issue of time zone. For any given moment, the date and time-of-day both vary around the globe by time zone. You cannot talk about dates without talking about time 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][2] 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 ) ;
Never assume 00:00:00
Also, do not assume the day starts at 00:00:00. Because of anomalies such as Daylight Saving Time (DST), the day may start at another time, such as 01:00:00. Let java.time determine the first moment of the day. Specify a time zone to yield a ZonedDateTime object representing a specific moment.
ZonedDateTime startOfToday = LocalDate.now( z ).atStartOfDay( z ) ;
ZonedDateTime startOfYesterday = startOfToday.toLocalDate().minusDays( 1 ).atStartOfDay( z ) ;
For querying database, it is often best to use UTC values. To adjust from our time zone to UTC, simply extract a Instant.
Instant start = startOfToday.toInstant() ;
Instant stop = startOfYesterday.toInstant() ;
Ready to query database. Using Half-Open approach here where beginning is inclusive while ending is exclusive. So, do not use SQL BETWEEN.
// SQL for SELECT WHERE when_field >= ? AND when_field < ?
myPreparedStatement.setObject( 1 , start ) ;
myPreparedStatement.setObject( 2 , stop ) ;
Comparing dates
If you just want to check the age of a retrieved moment, retrieve an Instant.
Instant instant = myResultSet.getObject( … , Instant.class ) ;
Apply a time zone to get a ZonedDateTime. Then extract the date-only value.
ZonedDateTime zdt = instant.atZone( z ) ;
LocalDate ld = zdt.toLocalDate() ; // Extract the date-only value.
Compare to today's date.
LocalDate yesterday = LocalDate.now( z ).minusDays( 1 ) ; // Subtract one day from today to get yesterday.
Boolean retrievedDateIsYesterday = ld.isEqual( yesterday ) ;
If you work much with spans-of-time, see the Interval and LocalDateRange classes in the ThreeTen-Extra project linked below.
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.

Android Calendar add day

I have an array String populated by data taken from the database.
Now for each row of the array I want to add a day to the calendar, the line "0" day today, the line "1" tomorrow, the line "2" after tomorrow etc ..
I created this code that controls the position of each element of the array, but how I add the days?
thanks
Calendar prova = Calendar.getInstance();
int size = id_op.length;
for(int i = 0; i< size; i++){
}
You can just get the time in milliseconds and then add a day worth of milliseconds to it.
Calendar prova = Calendar.getInstance();
int size = id_op.length;
for(int i = 0; i< size; i++){
Long time = prova.getTimeInMillis();
time = time + 86400000;
prova.setTimeInMillis(time);
}
tl;dr
new ArrayList<>().add(
LocalDate.now().plusDays( 1 )
)
java.time
You are using troublesome old Calendar class that is now legacy, supplanted by 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.
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.
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 ) ;
List
Generally better to use Java Collections than primitive arrays.
You can optionally specify the initial capacity of the ArrayList to avoid the performance penalty of the ArrayList resizing itself as you add more items.
int initialCapacity = … ;
List< LocalDate > dates = new ArrayList<>( initialCapacity ) ;
Add your dates.
dates.add( ld ) ; // Today, perhaps.
dates.add( ld.plusDays( 1 ) ; // Tomorrow.
dates.add( ld.plusDays( 2 ) ; // Day after tomorrow.
Or use a loop.
for( int i = 0 ; i <=10 ; i ++ ) {
dates.add( ld.plusDays( i ) ) ;
}
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.

Convert milliSeconds To Gregorian Calendar

I want to convert milliSeconds in long format to Gregorian Calendar.
By searching in the web, i use the code below:
public static String getStringDate(int julianDate){
GregorianCalendar gCal = new GregorianCalendar();
Time gTime = new Time();
gTime.setJulianDay(julianDate);
gCal.setTimeInMillis(gTime.toMillis(false));
String gString = Utils.getdf().format(gCal.getTime());
return gString;
}
public static SimpleDateFormat getdf(){
return new SimpleDateFormat("yyyy-MM-dd, HH:MM",Locale.US);
}
Yes, the code works but i find that only the date and the hour are correct but there are errors on minutes. Say if the thing happens on 2014-11-06, 14:00, it will give me 2014-11-06, 14:11. I want to know are there any solutions to modify it or it is not recommended to convert time into Gregorian Calendar. Many thanks!
The problem actually is very simple,
modify SimpleDateFormat("yyyy-MM-dd, HH:MM",Locale.US) with
SimpleDateFormat("yyyy-MM-dd, HH:mm",Locale.getDefault());
will solve the problem
tl;dr
Instant.ofEpochMilli( millis ) // Convert count-from-epoch into a `Instant` object for a moment in UTC.
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Adjust from UTC to a particular time zone. Same moment, different wall-clock time. Renders a `ZonedDateTime` object.
.format( // Generate a String in a particular format to represent the value of our `ZonedDateTime` object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd, HH:mm" )
)
java.time
The modern approach uses the java.time classes instead of those troublesome legacy classes.
Convert your count of milliseconds since the epoch reference of first moment of 1970 (1970-01-01T00:00Z) to a Instant object. Be aware that Instant is capable of finer granularity of nanoseconds.
Instant instant = Instant.ofEpochMilli( millis ) ;
That moment is in UTC. To adjust into another time zone, apply a ZoneId to get a ZonedDateTime.
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( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Generate a string in your desired format using a DateTimeFormatter object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd, HH:mm" , Locale.US ) ;
String output = zdt.format( f ) ;
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….

Get first Monday after certain date?

If my app received a certain date, how can I find out the date of first next Monday?
For example, I get the date 28 Sep 2011 and I have to find out the date of the first Monday after this date.
Do like this:
GregorianCalendar date = new GregorianCalendar( year, month, day );
while( date.get( Calendar.DAY_OF_WEEK ) != Calendar.MONDAY )
date.add( Calendar.DATE, 1 );
You can now extract the year, day and month from date. Remember that month is 0 based (e.g. January = 0, Febuary = 1, etc.) and day is not.
tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" ) ) // Capture the current date as seen by the people in a certain region (time zone).
.with( TemporalAdjusters.next( DayOfWeek.WEDNESDAY ) ) ; // Move to the following Wednesday.
Avoid .Date/.Calendar
The java.util.Date & .Calendar classes bundled with Java/Android are notoriously troublesome. Avoid them.
java.time – LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
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.
The time zone is crucial in determining the day and day-of-week. Use proper time zone names, never the 3 or 4 letter codes.
If you ignore time zone, the JVM’s current default time zone will be applied implicitly. This means different outputs when moving your app from one machine to another, or when a sys admin changes the time zone of host machine, or when any Java code in any thread of any app within the same JVM decides to call setDefault even during your app‘s execution.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
TemporalAdjuster
Use a TemporalAdjuster to get next day-of-week. We can use an implementation in the TemporalAdjusters (note the plural 's') class: next( DayOfWeek ). Pass an object from the handy DayOfWeek enum.
LocalDate nextWednesday = today.with( TemporalAdjusters.next( DayOfWeek.WEDNESDAY ) );
If you wanted today to be found if it is a Wednesday, then call the similar adjuster TemporalAdjusters.nextOrSame( DayOfWeek ).
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….
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section left intact as history.
Here is example code using Joda-Time 2.7.
Get the time zone you desire/expect. If working in UTC, use the constant DateTimeZone.UTC.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
Get the date-time value you need. Here I am using the current moment.
DateTime dateTime = DateTime.now( zone );
Specify the future day-of-week you want. Note that Joda-Time uses the sensible # 1 for first day of week, rather than zero-based counting found in java.util.Calendar. First day of week is Monday, per international norms and standards (not Sunday as is common in United States).
int dayOfWeek = DateTimeConstants.SATURDAY;
The withDayOfWeek command may go back in time. So we use a ternary operator (?:) to make sure we go forwards in time by adding a week as needed.
DateTime future = ( dateTime.getDayOfWeek() < dayOfWeek )
? dateTime.withDayOfWeek( dayOfWeek )
: dateTime.plusWeeks( 1 ).withDayOfWeek( dayOfWeek );
You may want to adjust the time-of-day to the first moment of the day to emphasize the focus on the day rather than a particular moment within the day.
future = future.withTimeAtStartOfDay(); // Adjust time-of-day to first moment of the day to stress the focus on the entire day rather than a specific moment within the day. Or use `LocalDate` class.
Dump to console.
System.out.println( "Next day # " + dayOfWeek + " after " + dateTime + " is " + future );
When run.
Next day # 6 after 2015-04-18T16:03:36.146-04:00 is 2015-04-25T00:00:00.000-04:00
LocalDate
If you only care about the date without any time of day, you can write similar code with the LocalDate class rather than DateTime. The "Local" means the date could apply to any locality, rather than having a specific time zone.
LocalDate localDate = new LocalDate( 2011 , 9 , 28 );
int dayOfWeek = DateTimeConstants.MONDAY;
LocalDate future = ( localDate.getDayOfWeek() < dayOfWeek )
? localDate.withDayOfWeek( dayOfWeek )
: localDate.plusWeeks( 1 ).withDayOfWeek( dayOfWeek );
When run.
Next day # 1 after 2011-09-28 is 2011-10-03
Get Next Monday from the date given.
//code provided by MadProgrammer at http://stackoverflow.com/questions/24177516/get-first-next-monday-after-certain-date/24177555#24177555
Calendar date1 = Calendar.getInstance();
date1.set(2014, 05, 12);
while (date1.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
date1.add(Calendar.DATE, 1);
}
System.out.println(date1.getTime());
Which outputted...
Mon Jun 16 16:22:26 EST 2014
I recently developed Lamma which is designed to solve this use case. Simply call next(DayOfWeek.MONDAY) on io.lamma.Date object will return the next Monday.
System.out.println(new Date(2014, 6, 27).next(DayOfWeek.MONDAY)); // Date(2014,6,30)
you can use strtotime():
date('Y-m-d H:i:s', strtotime( "Next Monday", strtotime('28 Sep 2011')) );

Get day of the week from GregorianCalendar

I have a date and I need to know the day of the week, so I used a GregorianCalendar object but I get back some dates that are incorrect.
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
What am I doing wrong?
Thanks!
EDIT SOLUTION:
mont--;
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int i = calendar.get(Calendar.DAY_OF_WEEK);
if(i == 2){
dayOfTheWeek = "Mon";
} else if (i==3){
dayOfTheWeek = "Tue";
} else if (i==4){
dayOfTheWeek = "Wed";
} else if (i==5){
dayOfTheWeek = "Thu";
} else if (i==6){
dayOfTheWeek = "Fri";
} else if (i==7){
dayOfTheWeek = "Sat";
} else if (i==1){
dayOfTheWeek = "Sun";
}
TimeZone timezone = TimeZone.getDefault();
Calendar calendar = new GregorianCalendar(timezone);
calendar.set(year, month, day, hour, minute, second);
String monthName=calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.getDefault());//Locale.US);
String dayName=calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault());//Locale.US);
Joda-Time
I use Joda-Time library for all date/time related operations. Joda takes into account you locale and gets results accordingly:
import org.joda.time.DateTime;
DateTime date = new DateTime(year, month, day, 0, 0, 0);
or
DateTime date = DateTime().now();
Day of week (int):
date.getDayOfWeek();
Day of week (short String) using toString() and DateTimeFormat options:
date.toString("EE");
tl;dr
myGregCal // `GregorianCalendar` is a legacy class, supplanted by the modern `java.time.ZonedDateTime` class.
.toZonedDateTime() // Convert to `ZonedDateTime`.
.getDayOfWeek(). // Extract a `DayOfWeek` enum object, one of seven pre-defined objects, one for each day of the week.
.getDisplayName( // Automatically localize, generating a `String` to represent the name of the day of the week.
TextStyle.SHORT , // Specify how long or abbreviated.
Locale.US // Locale determines the human language and cultural norms used in localization.
) // Returns a `String` object.
Mon
LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) // Get current date for people in a certain region, without time-of-day and without time zone.
.getDayOfWeek() // Extract a `DayOfWeek` enum object.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Generate a string representing that day-of-week, localized using the human language and cultural norms of a particular locale.
lundi
java.time
Convert the troublesome old legacy java.util.GregorianCalendar object to a modern java.time object by calling new methods added to the old class.
ZonedDateTime zdt = myGregCal.toZonedDateTime();
Get the DayOfWeek enum object for that moment in that time zone.
DayOfWeek dow = zdt.getDayOfWeek();
dow.toString(): WEDNESDAY
Pass these DayOfWeek objects around your code rather than passing integers like 1-7 or strings like "MON". By using the enum objects you make your code more self-documenting, provide type-safety, and ensure a range of valid values.
For presentation to the user, ask the DayOfWeek object to translate the name of the day of the week to a human language defined in a Locale.
String output =
dow.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.CANADA_FRENCH
)
;
mercredi
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….

Categories

Resources