Java 从特定时间更新日期的每日计数器
我有两个日期,分别是“2018-01-01”开始日期和“2018-01-31”结束日期 我希望我的逻辑是,每天我的开始日期都会增加,直到2018-02-28。下面是我尝试的代码片段。如何解决此问题,因为开始日期应每天更改Java 从特定时间更新日期的每日计数器,java,date,java-calendar,Java,Date,Java Calendar,我有两个日期,分别是“2018-01-01”开始日期和“2018-01-31”结束日期 我希望我的逻辑是,每天我的开始日期都会增加,直到2018-02-28。下面是我尝试的代码片段。如何解决此问题,因为开始日期应每天更改 public class myclass { public static void main(String a[]) { try { String dt = "2008-01-01"; // Start date
public class myclass {
public static void main(String a[]) {
try {
String dt = "2008-01-01"; // Start date
String dt1 = "2008-01-31"; // End date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); //
System.out.println(dt);
}catch (Exception ex) {
ex.printStackTrace();
}
}
}
PS:该执行是实时的,在调度程序中每天运行,并根据给定日期的最终日期进行检查。还剩多少天
感谢Java 8的time API,您可以轻松实现
for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1))
{
...
}
Java8的时间API,可以轻松实现
for (LocalDate date = startDate; date.isBefore(endDate); date = date.plusDays(1))
{
...
}
您可以使用
java.util.Timer
类来实现此目的
在下面的节目中,我采取了不同的方法。我没有使用开始日期。我只需每天获取当前日期,并对照目标日期(本例中为“2019-02-10”)进行检查。看看这是否符合您的要求
(使用5秒(毫秒)
测试程序。)
您可以使用
java.util.Timer
类来实现此目的
在下面的节目中,我采取了不同的方法。我没有使用开始日期。我只需每天获取当前日期,并对照目标日期(本例中为“2019-02-10”)进行检查。看看这是否符合您的要求
(使用5秒(毫秒)
测试程序。)
Runnable
定义作为一个团队需要完成的工作
然后使用每分钟左右运行一次,检查当前日期和目标日期。如果倒计时已增加,则更新GUI中的显示。如果没有,则什么也不做,让Runnable
在另一分钟后再次运行
看
每次安排一个新的Runnable
,而不是自动重复,以便将延迟设置为计算的时间量,直到下一个午夜,这样会更有效。这样,遗嘱执行人就可以整天睡觉,而不是分秒必争。但是,如果用户的时钟更新到明显不同的当前时间,或者如果用户当前的默认时区发生变化(如果您依赖默认时区而不是明确设置默认时区),这种方法可能会失控。鉴于此Runnable
需要做的事情很少(只需检查当前日期和计算剩余天数),因此没有实际理由不让它每一两分钟运行一次(无论您对用户的最新更新的最小容忍时间有多长-这是您应用程序管理的一项业务政策)
LocalDate
该类表示一个只包含日期的值,不包含一天中的时间,也不包含或
时区对于确定日期至关重要。在任何一个特定的时刻,世界各地的日期都因地区而异。例如,中午夜后几分钟是新的一天,而中仍然是“昨天”
如果未指定时区,JVM将隐式应用其当前默认时区。该默认值可能在运行时(!)期间出现,因此您的结果可能会有所不同。最好将所需/预期时区明确指定为参数
以大陆/地区
的格式指定,例如美国/蒙特利尔
,非洲/卡萨布兰卡
,或太平洋/奥克兰
。切勿使用2-4个字母的缩写,如EST
或IST
,因为它们不是真正的时区,也不是标准化的,甚至不是唯一的(!)
实例
这是一个完整的例子。有关详细信息,请搜索堆栈溢出。ScheduledExecutorService
的使用已经介绍了很多次
package work.basil.example;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DailyCountdown implements Runnable {
private LocalDate dueDate;
private Long daysRemaining;
public DailyCountdown ( LocalDate dueDate ) {
this.dueDate = dueDate;
}
@Override
public void run () {
try {
System.out.println( "DEBUG - Running the DailyCountdown::run method at " + Instant.now() );
ZoneId z = ZoneId.of( "America/Montreal" ); // Or ZoneId.systemDefault() to rely on the JVM’s current default time zone.
LocalDate today = LocalDate.now( z );
Long count = ChronoUnit.DAYS.between( today , this.dueDate );
if ( Objects.isNull( this.daysRemaining ) ) {
this.daysRemaining = ( count - 1 );
}
if ( this.daysRemaining.equals( count ) ) {
// Do nothing.
} else {
// … Schedule on another thread for the GUI to update with the new number.
this.daysRemaining = count;
}
} catch ( Exception e ) {
// Log this unexpected exception, and notify sysadmin.
// Any uncaught exception reaching the scheduled executor service would have caused it to silently halt any further scheduling.
}
}
public static void main ( String[] args ) {
// Put this code where ever appropriate, when setting up your GUI after the app launches.
Runnable r = new DailyCountdown( LocalDate.of( 2018 , Month.FEBRUARY , 15 ) );
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleWithFixedDelay( r , 0L , 1L , TimeUnit.MINUTES );
// Be sure to gracefully shutdown the ScheduledExecutorService when your program is stopping. Otherwise, the executor may continue running indefinitely on the background thread.
try {
Thread.sleep( TimeUnit.MINUTES.toMillis( 7 ) ); // Sleep 7 minutes to let the background thread do its thing.
} catch ( InterruptedException e ) {
System.out.println( "The `main` thread was woken early from sleep." );
}
ses.shutdown();
System.out.println( "App is exiting at " + Instant.now() ) ;
}
}
Runnable
定义作为一个团队需要完成的工作
然后使用每分钟左右运行一次,检查当前日期和目标日期。如果倒计时已增加,则更新GUI中的显示。如果没有,则什么也不做,让Runnable
在另一分钟后再次运行
看
每次安排一个新的Runnable
,而不是自动重复,以便将延迟设置为计算的时间量,直到下一个午夜,这样会更有效。这样,遗嘱执行人就可以整天睡觉,而不是分秒必争。但是,如果用户的时钟更新到明显不同的当前时间,或者如果用户当前的默认时区发生变化(如果您依赖默认时区而不是明确设置默认时区),这种方法可能会失控。鉴于此Runnable
需要做的事情很少(只需检查当前日期和计算剩余天数),因此没有实际理由不让它每一两分钟运行一次(无论您对用户的最新更新的最小容忍时间有多长-这是您应用程序管理的一项业务政策)
LocalDate
该类表示一个只包含日期的值,不包含一天中的时间,也不包含或
时区对于确定日期至关重要。在任何一个特定的时刻,世界各地的日期都因地区而异。例如,中午夜后几分钟是新的一天,而中仍然是“昨天”
如果未指定时区,JVM将隐式应用其当前默认时区。该默认值可能在运行时(!)期间出现,因此您的结果可能会有所不同。最好将所需/预期时区明确指定为参数
以大陆/地区
的格式指定,例如美国/蒙特利尔
,非洲/卡萨布兰卡
,或太平洋/奥克兰
。切勿使用2-4个字母的缩写,如EST
或IST
,因为它们不是真正的时区,也不是标准化的,甚至不是唯一的(!)
实例
这是一个完整的例子。有关详细信息,请搜索堆栈溢出。ScheduledExecutorService
的使用已经介绍了很多次
package work.basil.example;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DailyCountdown implements Runnable {
private LocalDate dueDate;
private Long daysRemaining;
public DailyCountdown ( LocalDate dueDate ) {
this.dueDate = dueDate;
}
@Override
public void run () {
try {
System.out.println( "DEBUG - Running the DailyCountdown::run method at " + Instant.now() );
ZoneId z = ZoneId.of( "America/Montreal" ); // Or ZoneId.systemDefault() to rely on the JVM’s current default time zone.
LocalDate today = LocalDate.now( z );
Long count = ChronoUnit.DAYS.between( today , this.dueDate );
if ( Objects.isNull( this.daysRemaining ) ) {
this.daysRemaining = ( count - 1 );
}
if ( this.daysRemaining.equals( count ) ) {
// Do nothing.
} else {
// … Schedule on another thread for the GUI to update with the new number.
this.daysRemaining = count;
}
} catch ( Exception e ) {
// Log this unexpected exception, and notify sysadmin.
// Any uncaught exception reaching the scheduled executor service would have caused it to silently halt any further scheduling.
}
}
public static void main ( String[] args ) {
// Put this code where ever appropriate, when setting up your GUI after the app launches.
Runnable r = new DailyCountdown( LocalDate.of( 2018 , Month.FEBRUARY , 15 ) );
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleWithFixedDelay( r , 0L , 1L , TimeUnit.MINUTES );
// Be sure to gracefully shutdown the ScheduledExecutorService when your program is stopping. Otherwise, the executor may continue running indefinitely on the background thread.
try {
Thread.sleep( TimeUnit.MINUTES.toMillis( 7 ) ); // Sleep 7 minutes to let the background thread do its thing.
} catch ( InterruptedException e ) {
System.out.println( "The `main` thread was woken early from sleep." );
}
ses.shutdown();
System.out.println( "App is exiting at " + Instant.now() ) ;
}
}
你想实时更新日期吗?我的意思是,这个程序实际上会运行几个月,每天都会更新
dt
?另一件事,dt1
(结束日期)与该程序的相关性是什么?您好,是实时的,在调度程序中,它每天运行并检查
package work.basil.example;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class DailyCountdown implements Runnable {
private LocalDate dueDate;
private Long daysRemaining;
public DailyCountdown ( LocalDate dueDate ) {
this.dueDate = dueDate;
}
@Override
public void run () {
try {
System.out.println( "DEBUG - Running the DailyCountdown::run method at " + Instant.now() );
ZoneId z = ZoneId.of( "America/Montreal" ); // Or ZoneId.systemDefault() to rely on the JVM’s current default time zone.
LocalDate today = LocalDate.now( z );
Long count = ChronoUnit.DAYS.between( today , this.dueDate );
if ( Objects.isNull( this.daysRemaining ) ) {
this.daysRemaining = ( count - 1 );
}
if ( this.daysRemaining.equals( count ) ) {
// Do nothing.
} else {
// … Schedule on another thread for the GUI to update with the new number.
this.daysRemaining = count;
}
} catch ( Exception e ) {
// Log this unexpected exception, and notify sysadmin.
// Any uncaught exception reaching the scheduled executor service would have caused it to silently halt any further scheduling.
}
}
public static void main ( String[] args ) {
// Put this code where ever appropriate, when setting up your GUI after the app launches.
Runnable r = new DailyCountdown( LocalDate.of( 2018 , Month.FEBRUARY , 15 ) );
ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
ses.scheduleWithFixedDelay( r , 0L , 1L , TimeUnit.MINUTES );
// Be sure to gracefully shutdown the ScheduledExecutorService when your program is stopping. Otherwise, the executor may continue running indefinitely on the background thread.
try {
Thread.sleep( TimeUnit.MINUTES.toMillis( 7 ) ); // Sleep 7 minutes to let the background thread do its thing.
} catch ( InterruptedException e ) {
System.out.println( "The `main` thread was woken early from sleep." );
}
ses.shutdown();
System.out.println( "App is exiting at " + Instant.now() ) ;
}
}