在Android中比较两次

时间:2014-12-16 12:39:33

标签: java android datetime time

我知道这是一个讨论很多的话题,但我认为我有一个非常具体的问题。

我存储数据库中商店的开启和关闭时间以及GPS坐标。如果商店是开放的,我希望能够在绿色标记的地图上显示商店,如果关闭,则可以显示红色(当前时间)。

我的问题是我使用string.compareTo(string)方法来了解商店是关闭还是打开。我们假设我们星期一,商店早上02:00(星期二早上)关闭,当前时间是23:00。从02:00开始,我该怎么知道商店仍然营业? 23:00?

感谢您的回答,

阿诺

1 个答案:

答案 0 :(得分:3)

编辑:我正在编辑我的答案,以便更好地了解我的意思。此外,尝试备份一秒并重新考虑存储数据结构的方式。这是编程中非常重要的一部分,在大多数情况下可能是糟糕设计和良好设计实现之间的差异。

将时间存储为字符串不是一个好主意,但在您的情况下,您应该做的事情(我认为)是这样的:(此代码假定商店开放和关闭时间的小时数指的是同一天now

// Get the current time. 
Calendar now = Calendar.getInstance();

// Create the opening time. 
Calendar openingTime = Calendar.getInstance();

// Set the opening hours. (IMPORTANT: It will be very useful to know the day also).
openingTime.set(Calendar.HOUR_OF_DAY, storeOpeningTime); // (storeOpeningTime is in 24-hours format so for 10PM use 22).

// Check that the store "was opened" today. 
if (now.before(openingTime)) {
    return CLOSED; 
} 

// If the store "was opened" today check that it's not closed already ("tricky" part). 
// Create the closing time and closing time for the store. 
Calendar closingTime = Calendar.getInstance();

// Check if we are in the AM part. 
if (storeClosingTime < 12 // Closing time is in the AM part.
    && storeClosingTime < openingTime // Closing time is before opening time, meaning next day.
    // now and closingTime is the same day (edge case for if we passed midnight when getting closingTime)
    && closingTime.get(Calendar.DAY_OF_WEEK) == now.get(Calendar.DAY_OF_WEEK)) {

    // Closing time is next day.
    closingTime.add(Calendar.DAY_OF_WEEK, 1);
} 

// Set the closing hours. 
closingTime.set(Calendar.HOUR_OF_DAY, storeClosingTime); // (storeClosingTime is in 24-hours format so for 10PM use 22).

// Check if the store is not closed yet. 
if (now.before(closingTime)) {
    return OPEN; 
} 

// Store is closed. 
return CLOSED;

我还没有对此进行测试,但我认为根据您的问题以及如何保存开始和结束时间,这应该可行。

重要:您可以对代码进行更多边缘情况和调整以改进它,但我现在没有足够的时间来完成它。我想给出一个总体指导手来解决你的问题。处理时间和日期永远不会有趣,你需要记住很多元素,如时区和冬季和夏季在不同国家的时钟转换。这不是任何完成的实现,并且使其达到完成状态并不简单。

相关问题