[英]Java: How can I manipulate date to add days or months without using Calendar?
I have a simple function that compares two dates, if the two dates are equal - I want to add 7 days to one of the dates, or add a month depending on the scenario.我有一个简单的 function 比较两个日期,如果两个日期相等 - 我想将其中一个日期添加 7 天,或者根据情况添加一个月。 I have two dates formatted using simpleDateFormat that are converted to date from a string, then I compare them like so
我有两个使用 simpleDateFormat 格式化的日期,它们从字符串转换为日期,然后我像这样比较它们
Date dateExpired = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(expDate);
Date dateEffective = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(effDate);
Comparison method:比较方法:
if(dateExpired.before(dateEffective) || dateExpired.equals(dateEffective)) {
System.out.println("Same date for effective and expired");
}
Inside my comparison, I want to make the update.在我的比较中,我想进行更新。 Can anyone tell me how to do this?
谁能告诉我该怎么做?
Never use Calendar
, part of the terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.永远不要使用
Calendar
,这是几年前被 JSR 310 中定义的现代java.time类所取代的糟糕日期时间类的一部分。
Never put single-quote marks around the Z
in your date-time formatting pattern.切勿在日期时间格式模式中的
Z
周围加上单引号。 That letter indicates an offset-from-UTC of zero hours-minutes-seconds.该字母表示与 UTC 的偏移量为零时分秒。 Your quotes are discarding valuable information.
您的报价正在丢弃有价值的信息。
Your input strings are apparently in standard ISO 8601 format.您的输入字符串显然采用标准 ISO 8601 格式。 The java.time classes use the standard formats by default when when parsing/generating text.
java.time类在解析/生成文本时默认使用标准格式。 So no need to specify a formatting pattern.
所以不需要指定格式模式。
Parse your inputs as Instant
objects to represent a moment as seen in UTC.将您的输入解析为
Instant
对象以表示在 UTC 中看到的时刻。
Instant expirationUtc = Instant.parse( x ) ;
Instant effectiveUtc = Instant.parse( y ) ;
For any given moment, the date varies around the globe by time zone.对于任何给定的时刻,日期在全球范围内因时区而异。 It can be “tomorrow” in Tokyo Japan while simultaneously “yesterday” in Toledo Ohio US.
在日本东京可能是“明天”,而在美国俄亥俄州托莱多可能是“昨天”。
So you must adjust your inputs to the time zone by which you want to perceive the date.因此,您必须将输入调整为您想要感知日期的时区。
ZoneId z = ZoneId.of( "America/Edmonton" ) ;
ZonedDateTime expiration = expirationUtc.atZone( z ) ;
ZonedDateTime effective = effectiveUtc.atZone( z ) ;
Test for equality of dates.测试日期是否相等。 Extract the date portion to compare.
提取日期部分进行比较。
if( expiration.toLocalDate().isEqual( effective.toLocalDate() ) ) {…}
Represent a span of time using Period
class, for your month or week.使用
Period
class 表示您的月或周的时间跨度。
Period period = Period.ofWeeks( 1 ) ;
ZonedDateTime later = expiration.plus( period ) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.