Calendar set DAY_OF_WEEK not correct - android

Hi i have some problem with DAY_OF_WEEK. After research but don't know why.
Input date is :
30/01/2016 - SATURDAY
After run :
calendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
Output :
31/01/2016 - SUNDAY(Wrong).
I want it must 30/01/2016 - SATURDAY,
Please help me ?

try by passing Date
Calendar calendar = Calendar.getInstance;
calendar.set(2016, Calendar.JANUARY, 30);
or try this too
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
for(int i=0; i<7; i++)
{
System.out.print("Start Date : " + c.getTime() + ", ");
c.add(Calendar.DAY_OF_WEEK, 6);
}

tl;dr
LocalDate.of( 2016 , Month.JANUARY , 30 )
.with( TemporalAdjusters.next( DayOfWeek.SATURDAY ) )
2016-02-06
java.time
The modern approach uses java.time classes rather than the troublesome old Calendar class that is now legacy.
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 ) ;
Adjuster
To move from one date to another, use a TemporalAdjuster implementation found in TemporalAdjusters class. Specify the desired day-of-week using [DayOfWeek][2] enum.
LocalDate previousOrSameMonday = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.SATURDAY ) ) ;
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….

Related

Days of the week on Android

I'm working on an Android app where I need to display the days of the week from the calendar. Can I do that using the calendar API ? or there is a library that can I use ?
Thanks
For date handling in Android, I recommend 310ABP, a port of the Java 8 new date APIs for Android.
Use Calendar object to get these things done.
You could use the JodaTime library to display the current day of the week.
LocalDate newDate = new LocalDate();
int dayOfWeek = newDate.getDayOfWeek();
or there is a library that can I use ?
Yes. Use the back-port of the java.time classes. See "Android" item below.
Using java.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.
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 );
TemporalAdjuster
To get the first day of the week, (a) decide what is the first day of the week for you, (b) use a TemporalAdjuster implementation defined in TemporalAdjusters to get the date for a specific [DayOfWeek][6] enum object.
LocalDate ld = today.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) ) ;
To get a week’s worth of dates, add a day at a time.
LocalDate localDate = ld ; // Initialize our looping variable.
List<LocalDate> dates = new ArrayList<>( 7 ) ;
for( int i = 0 , i < 7 , i ++ ) { // Loop seven times, to cover a week.
localDate = localDate.plusDays( i );
dates.add( localDate ) ;
}
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….

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.

Calendar Time Not setting up

I am trying to set the calendar hour and minute by using the following code
Calendar c=Calendar.getInstance();
c.set(Calendar.HOUR,4);
c.set(Calendar.MINUTE, 23);
but it is always displaying 11 as hour and 12 as minute.
tl;dr
ZonedDateTime.of( // Represent a moment on the timeline adjusted into a particular time zone.
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) , // Capture the current date for a particular time zone.
LocalTime.of( 4 , 23 ) , // Hard-code the time-of-day value desired. Will be adjusted as needed to handle anomalies such as DST.
ZoneId.of( "Pacific/Auckland" ) // Apply a particular time zone to this date-time.
)
java.time
You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
You seem to want the current date with a specific time-of-day.
You ignore the crucial issue of 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" ) ;
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.
Determine today’s current date for a particular time zone.
LocalDate today = LocalDate.now( z ) ;
Represent your target time-of-day.
LocalTime lt = LocalTime.of( 4 , 23 ) ;
Combine with zone to get a ZonedDateTime. If your time-of-day is not valid for that date in that zone because of anomalies such as Daylight Saving Time (DST), the class automatically adjusts the time.
ZonedDateTime zdt = ZonedDateTime.of( today , lt , z ) ;
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….

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….

How to get localization of day in week

I couldnt find a symbol for that in SimpleDateFormat
How can I get the current day's localized name?
For example: Monday: 1. day of week ; Tuesday: 2.day, wednesday:3.day .....
I want to get Presentation Number "1" instead of Monday ...
As per other questions, you don't need SimpleDateFormat to get the numeric day of the week - that is provided by Calendar directly via the DAY_OF_WEEK field (which goes from 1 to 7 where 1 is SUNDAY and 7 is SATURDAY):
Calendar today = Calendar.getInstance();
int dayOfWeek = today.get(Calendar.DAY_OF_WEEK);
// Day of Week is a number between 1 and 7 where 1 is Sunday.
int dayOfWeekMondayFirst = (dayOfWeek + 5) % 7 + 1;
tl;dr
For the number 1-7, meaning Monday-Sunday, for today:
LocalDate.now().getDayOfWeek().getValue()
For the localized name of the day of the week:
LocalDate // Represent a date-only, without time-of-day and without time zone.
.now( // Get today’s current date as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Africa/Tunis" ) // Specify time zone.
) // Returns a `LocalDate`.
.getDayOfWeek() // Returns one of seven `DayOfWeek` enum objects.
.getDisplayName( // Localize the name of the day-of-week.
TextStyle.FULL , // How long or abbreviated should the localized string be.
Locale.UK // Specify a `Locale` to determine the human language and cultural norms to use in localizing.
) // Returns a string.
Monday
java.time
The modern approach uses the java.time classes that long ago supplanted the terrible legacy date-time classes such as SimpleDateFormat.
To get the day-of-week today, we need the 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.
DayOfWeek
The DayOfWeek enum pre-defines a set of seven objects, one for each day of the week.
Ask the LocalDate object for its DayOfWeek.
DayOfWeek dow = ld.getDayOfWeek() ;
Ask the DayOfWeek object to automatically localize its name. The DayOfWeek::getDisplayName method translates the name of the day into any human language specified by a Locale such as Locale.US or Locale.CANADA_FRENCH.
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );
lundi
Or, in US English.
String output = dow.getDisplayName( TextStyle.FULL , Locale.US );
Monday
To get the number of the day-of-week, where Monday-Sunday is 1-7 per the ISO 8601 standard, ask the DayOfWeek enum object for its value.
int dowNumber = dow.getValue() ; // 1-7 for Monday-Sunday.
To get the number 1-7 as part of a larger formatting pattern use e or c as directed in the DateTimeFormatter class.
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.

Categories

Resources