‘now’是否在一个”start – end”字符串中?

huangapple go评论67阅读模式
英文:

Is 'now' within a "start - end" string?

问题

我有类似以下示例的时间范围字符串:

"10:00 AM - 8:00 PM"

我知道我们始终会处理EST时区。

我正在寻找一种简单的处理方法,以便我可以检查"现在"是否在时间范围内。

我的初步想法是需要在"-"上对字符串进行分割,修剪字符串,然后使用SimpleDateFormat将"10:00 AM"和"8:00 PM"转换为时间对象。然后我会检查"现在"是否在上午10点之后,下午8点之前。

我认为可能有一个更简单的方法在Java库中处理所有这些,并返回一个布尔值true/false。有人有建议吗?

提前感谢!

英文:

I have timerange strings like the following example:

"10:00 AM - 8:00 PM"

I know we're always going to be dealing with EST.

I'm looking for a simple way of handling parsing this so that I can check if "now" is within the time range.

My initial thought is I need to do a string split on the "-", trim the strings, and then use simpledateformat to take "10:00 AM" and "8:00 PM" into time objects. From there I would check if "now" is after 10am, and before 8pm.

My thought is there might be a simpler method in a java library to handle all of this and return a boolean true/false. Does anyone have suggestions?

Thanks in advance!

答案1

得分: 3

只返回翻译好的部分:

没有另一种更简单的方法尝试类似这样的东西

static boolean isInBetween(LocalTime timeToCheck, String bounds){
    String[] timebounds = bounds.split("-", 0);
    LocalTime now = timeToCheck;
    LocalTime start = LocalTime.parse(timebounds[0].substring(0, timebounds[0].length() - 1), DateTimeFormatter.ofPattern("hh:mm a", Locale.US));
    LocalTime end = LocalTime.parse(timebounds[1].substring(1), DateTimeFormatter.ofPattern("hh:mm a", Locale.US));
    return now.isAfter(start) && now.isBefore(end);
}

做一些检查以确保数组不为空以及给定的 LocalTime 也不为空
英文:

There is no another easier way, try something like that:

  static boolean isInBetween(LocalTime timeToCheck, String bounds){
String[] timebounds = bounds.split("-", 0);
LocalTime now = timeToCheck;
LocalTime start = LocalTime.parse(timebounds[0].substring(0 , timebounds[0].length()-1), DateTimeFormatter.ofPattern("hh:mm a", Locale.US));
LocalTime end = LocalTime.parse(timebounds[1].substring(1), DateTimeFormatter.ofPattern("hh:mm a", Locale.US)) ;
    return now.isAfter(start) && now.isBefore(end);
}

do some checking to make sure the array is not empty and neither is the LocalTime you give.

huangapple
  • 本文由 发表于 2020年8月8日 03:49:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/63308348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定