I need to count back 90 days, 120 days and 160 days for a few items. How would I code this?
I keep finding java code but that brings up errors when I am developing for android.
I need to take todays date and subtract the x amount of days and have it result be displayed on the screen nothing else. Thanks
You should use the Calendar class :
//Calendar set to the current date
Calendar calendar=Calendar.getInstance();
//rollback 90 days
calendar.add(Calendar.DAY_OF_YEAR, -90);
//now the date is 90 days back
Log.i("MyApp","90 days ago:"+calendar.getTime().toString());
Use the Calendar object...
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -90); //etc
tl;dr
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.minusDays( 90 )
java.time
Other answers here are outdated. The modern way is with java.time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
You can then add or subtract days.
LocalDate ago090 = today.minusDays( 90 ) ;
LocalDate ago120 = today.minusDays( 120 ) ;
LocalDate ago160 = today.minusDays( 160 ) ;
To generate a string in standard ISO 8601 format of YYYY-MM-DD, call toString. For other formats, search Stack Overflow for DateTimeFormatter class to see many examples and discussions.
String output = ago120.toString() ;
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 java.time.
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….
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.
You should be able to use the Calendar class to achieve what you want: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html.
You can then call on your calendar object with the current date .add(Calendar.DAY_OF_YEAR, -90); and so on.
Related
This question already has answers here:
Why is January month 0 in Java Calendar?
(18 answers)
Closed 2 years ago.
Calendar rightNow = Calendar.getInstance();
String month = String.valueOf(rightNow.get(Calendar.MONTH));
After the execution of the above snippet, month gets a value of 10 instead of 11. How come?
Months are indexed from 0 not 1 so 10 is November and 11 will be December.
They start from 0 - check the docs
As is clear by the many answers: the month starts with 0.
Here's a tip: you should be using SimpleDateFormat to get the String-representation of the month:
Calendar rightNow = Calendar.getInstance();
java.text.SimpleDateFormat df1 = new java.text.SimpleDateFormat("MM");
java.text.SimpleDateFormat df2 = new java.text.SimpleDateFormat("MMM");
java.text.SimpleDateFormat df3 = new java.text.SimpleDateFormat("MMMM");
System.out.println(df1.format(rightNow.getTime()));
System.out.println(df2.format(rightNow.getTime()));
System.out.println(df3.format(rightNow.getTime()));
Output:
11
Nov
November
Note: the output may vary, it is Locale-specific.
As several people have pointed out, months returned by the Calendar and Date classes in Java are indexed from 0 instead of 1. So 0 is January, and the current month, November, is 10.
You might wonder why this is the case. The origins lie with the POSIX standard functions ctime, gmtime and localtime, which accept or return a time_t structure with the following fields (from man 3 ctime):
int tm_mday; /* day of month (1 - 31) */
int tm_mon; /* month of year (0 - 11) */
int tm_year; /* year - 1900 */
This API was copied pretty much exactly into the Java Date class in Java 1.0, and from there mostly intact into the Calendar class in Java 1.1. Sun fixed the most glaring problem when they introduced Calendar – the fact that the year 2001 in the Gregorian calendar was represented by the value 101 in their Date class. But I'm not sure why they didn't change the day and month values to at least both be consistent in their indexing, either from zero or one. This inconsistency and related confusion still exists in Java (and C) to this day.
Months start from zero, like indexes for lists.
Therefore Jan = 0, Feb = 1, etc.
From the API:
The first month of the year is JANUARY
which is 0; the last depends on the
number of months in a year.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html
tl;dr
LocalDate.now() // Returns a date-only `LocalDate` object for the current month of the JVM’s current default time zone.
.getMonthValue() // Returns 1-12 for January-December.
Details
Other answers are correct but outdated.
The troublesome old date-time classes had many poor design choices and flaws. One was the zero-based counting of month numbers 0-11 rather than the obvious 1-12.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
Months 1-12
In java.time the month number is indeed the expected 1-12 for January-December.
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.
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(!).
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
int month = today.getMonthValue(); // Returns 1-12 as values.
If you want a date-time for a time zone, use ZonedDateTime object in the same way.
ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "America/Montreal" ) );
int month = now.getMonthValue(); // Returns 1-12 as values.
Convert legacy classes
If you have a GregorianCalendar object in hand, convert to ZonedDateTime using new toZonedDateTime method added to the old class. For more conversion info, see Convert java.util.Date to what “java.time” type?
ZonedDateTime zdt = myGregorianCalendar.toZonedDateTime();
int month = zdt.getMonthValue(); // Returns 1-12 as values.
Month enum
The java.time classes include the handy Month enum, by the way. Use instances of this class in your code rather than mere integers to make your code more self-documenting, provide type-safety, and ensure valid values.
Month month = today.getMonth(); // Returns an instant of `Month` rather than integer.
The Month enum offers useful methods such as generating a String with the localized name of the month.
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.
cal.get(Calendar.MONTH) + 1;
The above statement gives the exact number of the month. As get(Calendar.Month) returns month starting from 0, adding 1 to the result would give the correct output. And keep in mind to subtract 1 when setting the month.
cal.set(Calendar.MONTH, (8 - 1));
Or use the constant variables provided.
cal.set(Calendar.MONTH, Calendar.AUGUST);
It would be better to use
Calendar.JANUARY
which is zero ...
I have written a code for custom calendar where I am using calendar object.I have used the method getFirstDayOfWeek() to retrieve first day of every month.On loading every month the method "_calendar.getTime()" returns the first date. On every device it is returning correctly.But on samsung J7 it returns starting date of week as 2 . Here is my debugger log for samsung J7
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2016,MONTH=10,WEEK_OF_YEAR=41,WEEK_OF_MONTH=3,DAY_OF_MONTH=14,DAY_OF_YEAR=288,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=2,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=46,SECOND=58,MILLISECOND=199,ZONE_OFFSET=19800000,DST_OFFSET=0]
It says firstDayOfWeek = 2 , for rest of the devices it shows as 1. So any ideas for the solution?
Thanks.
Ok, I got the solution. Instead of using getFirstDayOfWeek() I passed 1 as parameter. So its working properly now.
_calendar.set(year, (month - 1), 1);
in place of
_calendar.set(year, (month - 1), _calendar.getFirstDayOfWeek());
tl;dr
You seem to conflate first-of-month with first-day-of-week.
The 2 is a hard-coded constant representing Monday.
Apparently your current default locale considers Monday to be the first day of the week.
Use java.time instead.
For first day of the week:
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.with( TemporalAdjusters.previousOrSame( DayOfWeek.MONDAY ) )
For first day of the month:
LocalDate.now( ZoneId.of( "Pacific/Auckland" ) )
.with( ChronoField.DAY_OF_MONTH , 1L )
Details
getFirstDayOfWeek() to retrieve first day of every month
You seem to be confusing first of the week with first of the month.
The first of the month is always 1 of course.
The first of the week is a day-of-week such as Sunday or Monday etc. The definition of the first day of the week in the Calendar class varies, depending on the Locale. For example, in much of North America, the first day is Sunday commonly. In much of Europe, the first day of the week is Monday.
If you fail to specify a Locale, the Calendar class implicitly applies the JVM’s current default locale. Apparently in your default locale the first day of the week is Monday. I deduce that because you report the number 2. If you explore the int constant Calendar.MONDAY, you find it is indeed a primitive int of value 2.
Avoid legacy date-time classes
The Calendar class has many poor design decisions. I consider this varying definition of day-of-week to be one of them. One of many reasons to avoid these troublesome old date-time classes such as Calendar and Date. These classes are now legacy, supplanted by the java.time classes.
Using java.time
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 );
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 enum object.
DayOfWeek firstDow = DayOfWeek.MONDAY ;
LocalDate ld = today.with( TemporalAdjusters.previousOrSame( firstDow ) ) ;
To get a LocalDate for a certain day of month, call the with method and pass an enum object from ChronoField.DAY_OF_MONTH.
LocalDate firstOfMonth = today.with( ChronoField.DAY_OF_MONTH , 1L ) ;
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….
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….
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….
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….