当我尝试在数据库中获得的日期加上30天时,出现此错误。
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date today = Calendar.getInstance().getTime();
String reportDate = df.format(today);
String endDay = rset.getString("vip_end");
endDay.add(Calendar.DAY_OF_MONTH, 30)
错误
Error:(76, 70) java: cannot find symbol
symbol: method add(int,int)
location: variable endDay of type java.lang.String
答案 0 :(得分:1)
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.now( // Capture the current date as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Asia/Tokyo" ) // Specify your time zone. Use proper `Continent/Region` names, never 2-4 character pseudo-zones such as IST or PST or EST or CST.
) // Returns a `LocalDate` object.
.plusDays( 30 ) // Add days to determine a later date. Returns a new `LocalDate` object rather than mutating the original.
.toString() // Generate text representing the value of this `LocalDate` object, in standard ISO 8601 format YYYY-MM-DD.
2019-06-30
add
上没有String
方法您宣布endDay
为String
。然后,您调用了方法add
。但是add
类上没有方法String
。因此,您的错误如错误消息中所述。
您正在使用可怕的日期时间类,这些类早在几年前就被现代的 java.time 类取代,并采用了JSR 310。
LocalDate
类表示没有日期,没有time zone或offset-from-UTC的仅日期值。
时区对于确定日期至关重要。 在任何给定的时刻,日期在全球各地都会发生变化。例如,Paris France午夜之后的几分钟是新的一天,而Montréal Québec仍然是“昨天”。
如果未指定时区,则JVM隐式应用其当前的默认时区。该默认值可能在运行时(!)期间change at any moment,因此您的结果可能会有所不同。最好将您的期望/期望时区明确指定为参数。如果紧急,请与您的用户确认区域。
以Continent/Region
的格式指定proper time zone name,例如America/Montreal
,Africa/Casablanca
或Pacific/Auckland
。切勿使用2-4个字母的缩写,例如EST
或IST
,因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
如果要使用JVM的当前默认时区,请提出要求并作为参数传递。如果省略,代码将变得难以理解,因为我们不确定您是否打算使用默认值,还是像许多程序员一样不知道该问题。
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
或指定日期。您可以用数字设置月份,一月至十二月的理智编号为1-12。
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.
或者更好的是,使用预定义的Month
枚举对象,每年的每个月使用一个。提示:在整个代码库中使用这些Month
对象,而不是仅使用整数,可以使您的代码更具自记录性,确保有效值并提供type-safety。 Year
和YearMonth
的同上。
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
您的输出格式为标准ISO 8601格式。 LocalDate
类中默认使用此格式来解析/生成字符串。因此,无需指定格式设置模式。
String output = LocalDate.of( 2019 , Month.JANUARY , 23 ).toString() ;
2019-01-23
添加30天。
LocalDate today = LocalDate.now( ZoneId.of( "Africa/Tunis" ) ) ;
LocalDate later = today.plusDays( 30 ) ;
java.time 类遵循immutable objects模式。因此,他们根据原始值返回一个新的新鲜对象。