繁体   English   中英

在Android中比较两次

[英]Compare two times in Android

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

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

我的问题是我正在使用string.compareTo(string)方法来知道商店是关闭还是打开。 假设我们是星期一,商店在早上(星期二上午)02:00关闭,当前时间是23:00。 我怎样才能知道商店从02:00 <23:00开始营业?

谢谢您的回答,

阿诺

编辑:我正在编辑我的答案,以更好地理解我的意思。 另外,请尝试备份一秒钟,然后重新考虑存储数据结构的方式。 这是编程中非常重要的部分,在大多数情况下,这可能是不良设计与良好设计实现之间的区别。

将时间存储为字符串不是一个好主意,但是在您的情况下,您应该做的(我认为)是这样的:(此代码假定商店的营业时间和关闭时间均指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;

我尚未对此进行测试,但是我认为根据您的问题以及如何节省打开和关闭时间,这应该可以工作。

重要提示 :您可以对代码进行更多改进和改进,但是现在我没有足够的时间来做。 我想提供一个一般性的指导来解决您的问题。 处理时间和日期从来都不是一件有趣的事,您需要牢记许多要素,例如不同国家的冬季和夏季的时区和时钟偏移。 无论如何,这不是一个完成的实现,要使其达到完成状态并不容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM