如何在Java中设置最后期限而不对值进行硬编码 [英] How to set a deadline in Java without hardcoding the values

查看:155
本文介绍了如何在Java中设置最后期限而不对值进行硬编码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要设置一个程序,将日期对象(例如日期对象1)的创建日期与另一个表示截止日期的将来日期或日期对象(例如日期对象2)进行比较。例如,如果我创建一个初始的datetime对象,我希望能够将当前的创建日期与该日期之后的18天(截止日期)进行比较,我不想对实际的日期和截止日期进行硬编码。它应该返回一个布尔值(当当前日期等于或晚于截止日期时为true,否则为false)。最终,我想将截止日期存储在外部数据库中,然后在适当的时候将所述截止日期与当前日期进行比较。

I need to set up a program that compares the date of creation of a date object(say date object 1), with another a future date or date object(say date object 2) that represents the deadline. For example, if i create an initial datetime object, I want to be able to compare the current date of creation with lets say, a date 18 days after said date(deadline).I don't want to hardcode the actual dates and deadlines. It should return a bool( true when current date is equal or later than the deadline date, false otherwise). Eventually, I'll want to store the date of the deadline in an external database, then when appropriate compare said deadline date with the current date.

我可以获取当前日期日期与下面的代码一起使用,但是不确定如何通过指定当前日期的 x天而不是对日期值进行硬编码来获取截止日期。

I can get the current date with the code below but unsure how to obtain a deadline day by specifyinging "x" days from the current date instead of hardcoding the date values.

我知道如何创建日期对象(如下所示),但我希望能够创建一个与当前创建日期相对应的截止日期对象,将截止日期存储在数据库中,同时不断将当前日期与截止日期进行比较。

I know how to create a date object(as show below) but i want to be able to create a deadline date object in correspondence to the current date of creation, store the deadline date in a database, while continually comparing the current date with the deadline date.

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(dtf.format(localDate)); //2016/11/16


推荐答案

要创建 非硬编码的截止日期

LocalDate currentDate = LocalDate.now();
LocalDate deadline = LocalDate.now().plusDays(10); // x = 10
storeDb(deadline);

然后稍后进行截止日期检查;

Then later for deadline check;

LocalDate deadline = getDeadlineFromDb();
LocalDate currentDate = LocalDate.now();
if (currentDate.isAfter(deadline)) {
    // deadline has passed
}

有关更多详细信息,请参见; Java 8日期/时间API简介

For more details check; Introduction to the Java 8 Date/Time API

这篇关于如何在Java中设置最后期限而不对值进行硬编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆