I'm have a problem going from january back to december I tried various things but im getting the nullexception. i'm using a button and put a mouselistener so everytime i click it, it decreament a month. but after january it won't decrement to december even i change the year before check the month. here's what I did.
Button btnNewButton = new Button(composite, SWT.NONE);
btnNewButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseUp(MouseEvent e) {
moveCalendar("down");
}
});
then here's my moveCalendar..
public void moveCalendar(String move)
{
Calendar cal = GregorianCalendar.getInstance();
resetBox();
if(move.equals("down") )
{
dummyMonth--;
if(dummyMonth < 0)
{
dummyMonth = 11;
dummyYear--;
}
}
else
{
dummyMonth++;
if(dummyMonth > 11)
{
dummyMonth = 0;
dummyYear++;
}
}
cal.set(Calendar.YEAR,dummyYear);
setYear(dummyYear);
cal.set(Calendar.MONTH,dummyMonth);
setMonth(dummyMonth);
int dy = getFirstDay(cal.get(Calendar.MONTH),cal.get(Calendar.YEAR));
int daysMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
populateCalendar(dy-1,daysMonth,cal.get(Calendar.DAY_OF_MONTH),dummyMonth);
}
I get nullexception.. any suggestion what's happening?
Try using the Joda-Time library.
It has much better support for date and time manipulation than the stock java classes — so much so that it's the basis for the new standard dates and times API introduced in Java 8. If you're using Java 8 or higher, use the java.time api instead.
In Joda-Time, you can easily move to the previous month with code like this:
YearMonth date = new YearMonth("2014-01");
date = date.minusMonths(1); //will equal 2013-11
Your question doesn't say whether you're just dealing with years and months, or with an exact date (year, month, and day) but either way you would use a minusMonths method, just with a different class (for an exact date use the LocalDate class, for example).
To integrate with the UI controls properly, you would populate the controls after you've finished manipulating the date object by setting each control to the correct value from the date object.
This approach will be much easier than dealing with Calendar.
Try using the Calendar.add() method, for example:
cal.add(Calendar.MONTH, -1);
See http://www.tutorialspoint.com/java/util/calendar_add.htm
tl;dr
LocalDate
.of( 2020 , Month.JANUARY , 20 )
.minusMonths( 1 )
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible Calendar & Date classes.
For a date-only value, without time-of-day and without time zone, use LocalDate.
LocalDate localDate = LocalDate.of( 2020 , Month.JANUARY , 20 ) ;
To do date-math, call the plus… & minus… methods.
LocalDate monthAgo = localDate.minusMonths( 1 ) ; // Get same day-of-month in the previous month.
Or use a Period to represent a span-of-time unattached to the timeline.
Period p = Period.ofMonths( 1 ) ;
LocalDate earlier = localDate.minus( p ) ;
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.
Used Java 8 Date and time API as follows :
LocalDateTime dt2= LocalDateTime.of(2019,10,20, 12,45);
System.out.println(dt2); //2019-10-20T12:45
System.out.println(dt2.minusMonths(11));//2018-11-20T12:45
Related
I have stored the date of a specific method each time it gets executed in ab sqlite database in 3 columns (one for the day, the month and the year).
Now I want to compare it to the date of the actutal day the user uses the app. With
Date currentTime = Calendar.getInstance().getTime()
I get this date, but how am I able to compare it to the strings I get from my database? Thank you!
Using java.time
Your Question is a duplicate of many others. So briefly…
Use java.time classes rather than the troublesome old legacy date-time classes. For Android, use libraries from the ThreeTen-Backport and ThreeTenABP projects.
Get today’s date.
ZoneId z = ZoneId.of( "America/Montreal" ) )
LocalDate today = LocalDate.now( z );
Get to parts of the date.
int y = today.getYear() ;
int m = today.getMonthValue() ;
int d = today.getDayOfMonth() ;
Query the database.
myPreparedStatement.setInt( 1 , y ) ;
myPreparedStatement.setInt( 2 , m ) ;
myPreparedStatement.setInt( 3 , d ) ;
As others suggested, you should be using date-time types in your database to store date-time values rather than mere ints for the pieces.
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.
Try this:
SimpleDateFormat formattedDate = new SimpleDateFormat("dd/MM/yyyy");
String strDate= formattedDate.format(date);
It will give you your date as shown in the Template. Now simply build a String out of your SQLite data in the same way (dd/MM/yyyy) and you cam simply compare them like shown in this post: https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
I can't print GregorianCalendar
package Tests;
import java.util.Date;
import java.util.GregorianCalendar;
public class Data
{
public static void main(String[] args)
{
GregorianCalendar time = new GregorianCalendar(1999, 2, 2);
System.out.println(time);
}
}
I receive this
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Belgrade",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=119,lastRule=java.util.SimpleTimeZone[id=Europe/Belgrade,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=?,YEAR=1999,MONTH=2,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=2,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]
How I can print it?
you can use this like :-
GregorianCalendar calendar = new GregorianCalendar();
Date now = calendar.getTime();
System.out.println(now);
or
Calendar cal2 = new GregorianCalendar(2010, 9, 26); // allocate with the specified date
cal2.get(Calendar.DAY_OF_WEEK); // 1 (Sunday) to 7 (Saturday)
when you call
System.out.println(time)
you've actually calling the toString() method of the Calendar instance (in this case, a GregorianCalendar one)
In order to have a properly formatted date, use SimpleDateFormat as stated in the Javadoc
https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
java.time
The modern solution uses the LocalDate class instead. Avoid GregorianCalendar as it is now obsolete.
LocalDate ld = LocalDate.of( 1999 , Month.FEBRUARY , 2 ) ;
ld.toString(): 1999-02-02
The toString method uses the standard ISO 8601 formats. For other formats, use the DateTimeFormatter class. Search Stack Overflow for more examples and discussion, as that has beeen covered many many times.
Generally best to let DateTimeFormatter automatically localize for you.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( locale ) ;
String output = ld.format( f ) ;
mardi 2 février 1999
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.
I'm trying to return a list of dates from these parameters :
LocalDate startDate
LocalDate endDate
Boolean monday ... sunday : booleans
For example :
startDate = 01/03/2016
endDate = 10/03/2016 (included)
Monday = true;
Tuesday = false;
Wednesday = false;
Thursday = true;
Friday = true;
Saturday = false;
Sunday = false;
List of dates returned : [03/03/2016, 04/03/2016, 07/03/2016, 10/03/2016]
Is there any libray i can use ? I've only managed to returned the dates between two dates, but i have no idea how to use the days also : (I'm using java 6)
public List<LocalDate> datesBetween(LocalDate start, LocalDate end) {
List<LocalDate> ret = new ArrayList<LocalDate>();
for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1)) {
ret.add(date);
}
return ret;
}
Java SE 8 Date and Time
Listing 1
Standard Java getter conventions are used in order to obtain values from Java SE 8 classes, as shown in Listing 2.
LocalDate theDate = timePoint.toLocalDate();
Month month = timePoint.getMonth();
int day = timePoint.getDayOfMonth();
timePoint.getSecond();
The problem is the signature of your method. The fact that days are passed in as names makes it very hard to do anything generic; it means you will need lots of code to solve the problem. You may want to consider passing in an array of size 7, or a list of day names that correspond to 'true' (omitting the others).
If you were to pass in a set of integers ranging from 0 to 6, encoding that a day of the week is active if it is inside the set, you could iterate through your time range and check whether the day was passed as active, or not. You could use method like date.getDayOfWeek() and set.contains().
Avoid old date-time classes
Avoid the old date-time classes bundled with the earliest versions of Java, such as java.util.Date/.Calendar. They are poorly designed, confusing, and troublesome.
java.time
The java.time framework built into Java 8 and later supplants the old date-time classes. See Tutorial.
For use with Java 6 & 7, check out the ThreeTen-Backport project ('ThreeTen' refers to JSR 310 defining java.time). For Android specifically, see the Android wrapper around the Backport, ThreeTenABP.
The new classes include LocalDate for a date-only value without time-of-day and without time zone. Another handy class you need is the enum DayOfWeek. Use these objects rather than strings to make your code type-safe, self-documenting, and localization-ready.
Reminder: Java provides special high-performance Set and Map implementations for enums, EnumSet and EnumMap.
EnumSet<DayOfWeek> dayOfWeekSet = EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY );
Define a date interval.
LocalDate start = LocalDate.of( 2016 , Month.MARCH , 1 );
LocalDate stop = start.plusDays( 10 );
Define a collection to keep our targeted dates.
List<LocalDate> localDates = new ArrayList<>();
Loop the days in that interval. In date-time work we commonly use the Half-Open approach where the beginning in inclusive while the ending is exclusive.
LocalDate localDate = start;
while ( localDate.isBefore( stop ) ) {
if ( dayOfWeekSet.contains ( localDate.getDayOfWeek() ) ) {
localDates.add( localDate );
}
// Prepare for next loop.
localDate = localDate.plusDays( 1 );
}
Dump to console.
System.out.println( "From: " + start + " to: " + stop + " the dates for days-of-week: " + dayOfWeekSet + " = " + localDates );
From: 2016-03-01 to: 2016-03-11 the dates for days-of-week: [TUESDAY, THURSDAY] = [2016-03-01, 2016-03-03, 2016-03-08, 2016-03-10]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
I have this code:
public static String formatMinSecOrHourMinSec(final String length) {
try {
final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss", Locale.GERMAN);
final Date date = hhmmss.parse(length);
final GregorianCalendar gc0 = new GregorianCalendar(Locale.GERMAN);
gc0.setTime(date);
if(gc0.getTimeInMillis() >= 3600 * 1000){
return hhmmss.format(gc0.getTime());
}else{
final SimpleDateFormat mmss = new SimpleDateFormat("mm:ss");
return mmss.format(gc0.getTime());
}
} catch (final ParseException e) {
LOGGER.debug("Konnte die Länge nicht parsen: " + length + "\n" + e);
return length;
}
}
I estimate that it returns 01:29:00 if length is set to 01:29:00 but it returns 29:00. This is because gc0.getTimeInMillis() returns one hour less (3600 * 1000) than expected. What am I doing wrong ?
this is because java.util.Date is using your default time zone. (print time in ms from date and you will see).
To fix it try:
final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss");
hhmmss.setTimeZone(TimeZone.getTimeZone("UTC"));
tl;dr
Do not conflate a span-of-time with a time-of-day. Two different concepts deserve two different classes. A span-of-time is represented by the Duration (or Period) class.
Duration
.ofHours( 1 )
.plusMinutes( 29 )
…or…
Duration
.parse( "PT1H29M" )
Wrong classes
First, you are using inappropriate classes. Apparently you are trying to track a span-of-time but are using time-of-day to do so. A span and a time are two different concepts. Mixing the two leads to ambiguity, confusion, and errors.
Second, you are using terrible old classes that were supplanted years ago by the java.time classes. Never use SimpleDateFormat, GregorianCalendar, etc.
Span-of-time
The correct class for a span-of-time in the range of hours-minutes-seconds is Duration. For a range of years-months-days, use Period.
You can instantiate your Duration from numbers of hours and minutes.
Duration d = Duration.ofHours( 1 ).plusMinutes( 29 ) ;
Or you can parse a string in standard ISO 8601 format, PnYnMnDTnHnMnS.
Duration d = Duration.parse( "PT1H29M" ) ;
Date-Time math
You can do math with date-time values. Perhaps you want to know when is an hour and twenty-nine minutes from now.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ; // Capture the current moment as seen though the wall-clock time used by the people of some particular region.
ZonedDateTime later = now.plus( d ) ; // Add a span-of-time to determine a later moment (or an earlier moment if the `Duration` is negative).
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 have a Date object in Java. Sometimes the date's year is set to 17. When I go to output it using a SimpleDateFormat, it gets printed out as 0017. All my years are going to be in the 2000's. Is there a way to check if the year is belowe a certain value and then add 2000 to it if it is? Then once you do that, how do you recreate the Date object to use the new year? Seems like everything in the Date object is deprecated.
I would use a Calendar:
Date myDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(myDate);
int year = cal.get(Calendar.YEAR);
if(year < 2000)
cal.add(Calendar.YEAR, 2000); // add two thousand years
If you use Calendar or Joda Time (a better choice) you can get and set the year (or other fields)
Your year shouldn't be 17 in the first place. I would try to correct the problem at source rather than patch it later.
First of all, Date.getYear returns CurrentYear - 1900, not 2000, and it looks like you'll want to do that increment every time.
But since it's deprecated, you shouldn't use it in the first place, if possible. The API recommends you use the calendar class instead: http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Calendar.html
java.time
If by Date you mean java.util.Date, that terribly designed class in now obsolete, years ago supplanted by the java.time classes defined in JSR 310.
Convert to its replacement, Instant, using new methods added to the old classes.
Instant instant = myJavaUtilDate.toInstant() ;
Both Instant and java.util.Date represent a moment in UTC. For any given moment, both time-of-day and date vary around the globe by zone. If you want to see the date through the wall-clock time of a particular time zone, apply ZoneId to get a ZonedDateTime.
ZoneID z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDatetTime zdt = instant.atZone( z ) ;
Now interrogate for the year.
int year = zdt.getYear() ;
Adjust. If that date in the different year is not valid (February 29 in non leap year), the ZonedDateTime class adjusts.
if( year < 1000 ) {
zdt = zdt.withYear( year + 2000 ) ; // You might also want to check for negative numbers. I'll omit that from this demo.
}
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.